Reputation: 1120
Suppose I have a method like this
+ (NSString *)stringWithObject:(id)object format:(NSString *)format
{
NSString *string = [NSString stringWithFormat:format, object];
NSLog(@"%@", string);
return string;
}
The object
parameter is never nil
but the format argument passed into the method might either be
NSString *formatWithPlaceholder = @"object: %@"
or
NSString *formatWithoutPlaceholder = @"No object";
so if formatWithoutPlaceholder
is passed into the method as the format argument, the console output is correct and there are no warnings or errors, but will this cause other problems? I feel like there is something wrong about the usage of stringWithFormat:
like this.
Upvotes: 3
Views: 321
Reputation: 726539
Nothing bad happens when the format string has fewer format specifiers than the number of parameters supplied: your code is valid for both format strings.
However, when the opposite situation happens (more format specifiers than the parameters) you get undefined behavior.
Upvotes: 5