によって返されるフォーマットされた文字列NSString initWithFormat:arguments:
が期待どおりであることを確認するには、引数と同じ数のフォーマット指定子があるかどうかを判断する必要があります。以下は(少し工夫され、高度に編集された)例です:
- (void)thingsForStuff:(CustomStuff)stuff, ...
{
NSString *format;
switch (stuff)
{
case CustomStuffTwo:
format = @"Two things: %@ and %@";
break;
case CustomStuffThree:
format = @"Three things: %@, %@, and %@";
break;
default:
format = @"Just one thing: %@";
break;
}
va_list args;
va_start(args, method);
// Want to check if format has the same number of %@s as there are args, but not sure how
NSString *formattedStuff = [[NSString alloc] initWithFormat:format arguments:args];
va_end(args);
NSLog(@"Things: %@", formattedStuff);
}
このメソッドを使用すると、[self thingsForStuff:CustomStuffTwo, @"Hello", @"World"]
ログに記録されます
「2つのこと:こんにちはと世界」
...しかし[self thingsForStuff:CustomStuffTwo, @"Hello"]
ログに記録します
「2つのこと:こんにちはと」
...それが起こる前に捕まえられることが好ましい何か。
文字列内のフォーマット指定子、できれば軽量/安価なものを数える方法はありますか?