objective-c 警告:格式字符串不是字符串文字(可能不安全)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22799731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Warning : Format string is not a string literal (potentially insecure)
提问by Evan
I get the warning in the NSLog line
我在 NSLog 行中收到警告
Format string is not a string literal(potentially insecure)
From the following code
从以下代码
NSMutableString *MarqueeMessage = [[NSMutableString alloc]init];
[MarqueeMessage appendString:@"Abc"];
NSString *immutableString = MarqueeMessage;
NSLog(immutableString);
May I ask why after I changed the line into the following code, the warning is gone?
请问为什么我把那行改成下面的代码后,警告就没有了?
NSLog(immutableString,nil);
回答by user3386109
That's just the compiler's way of saying, "Hey, do you really know what you're doing?" The compiler is concerned that the input string may contain a percent character %, and you haven't specified the corresponding argument. Obviously, that's not the case based on the code you've provided, but the compiler isn't smart enough to figure that out.
这只是编译器的说法,“嘿,你真的知道你在做什么吗?” 编译器担心输入字符串可能包含百分比字符%,而您尚未指定相应的参数。显然,根据您提供的代码,情况并非如此,但编译器不够聪明,无法弄清楚。
By adding an argument (which could be anything including a number, a string, or nil) you convince the compiler that you know what you're doing. The alternative way to make the compiler happy is to output the string with code like this.
通过添加参数(可以是数字、字符串或 nil 等任何内容),您可以让编译器相信您知道自己在做什么。让编译器满意的另一种方法是用这样的代码输出字符串。
NSLog( @"%@", immutableString );
The advantage of this method is that unexpected format specifiers in the string (e.g. %s) won't cause any problems.
这种方法的优点是字符串中意外的格式说明符(例如%s)不会导致任何问题。

