为了确保返回的格式化字符串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"]
将记录
“两件事:你好和世界”
...但[self thingsForStuff:CustomStuffTwo, @"Hello"]
会记录
“两件事:你好和”
......在它发生之前最好被抓住的东西。
有没有办法计算字符串中的格式说明符,最好是轻量级/便宜的?