To ensure that a formatted string returned by
- (void)thingsForStuff:(CustomStuff)stuff, ...
format = @"Two things: %@ and %@";
format = @"Three things: %@, %@, and %@";
format = @"Just one thing: %@";
// 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];
NSLog(@"Things: %@", formattedStuff);
[self thingsForStuff:CustomStuffTwo, @"Hello", @"World"]
"Two things: Hello and World"
[self thingsForStuff:CustomStuffTwo, @"Hello"]
"Two things: Hello and "
Is there a way to count the format specifiers in a string, preferably something lightweight/inexpensive?
Nope -- really isn't. At least, not if you want it to work across all possible format strings. You would have to duplicate the parser that is used by
stringWithFormat:. I.e. don't try to validate everything.
You could count the number of
%, but that would not catch things like
%% or other special cases. That may be good enough for your purposes.