如果stringWithFormat格式没有类型占位符,而是有参数,会发生什么

时间:2022-07-05 16:07:44

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

对象参数从来不是nil,但是传递给方法的格式参数可能是nil

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.

因此,如果formatWithoutPlaceholder作为format参数传递到方法中,控制台输出是正确的,并且没有任何警告或错误,但是这会导致其他问题吗?我觉得stringWithFormat的使用有些问题:像这样。

1 个解决方案

#1


5  

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.

然而,当相反的情况发生时(格式说明符多于参数),您将得到未定义的行为。

#1


5  

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.

然而,当相反的情况发生时(格式说明符多于参数),您将得到未定义的行为。