简体   繁体   English

NSString stringWithFormat格式警告

[英]NSString stringWithFormat format warning

I am probably using a wrong symbol for the NSString type to be included in another string. 我可能使用了错误的符号来将NSString类型包含在另一个字符串中。

const char* error; //it's set, not nil
NSLog([NSString stringWithFormat : @"Problem with SQL statement in \n %@ \n %@",sqlQuery,[NSString stringWithUTF8String:error]]);

The expression works, but I am getting this warning: 该表达式有效,但是我收到此警告:

Formatting string is not a string literal(potentially insecure)

Is there a way to get rid of the warnings? 有没有摆脱警告的方法?

According to NSLog implementation, the function expects a constant string or a format specifier string as it's first argument. 根据NSLog的实现,该函数将常量字符串或格式说明符字符串作为第一个参数。

You need to use: 您需要使用:

NSLog(@"Problem with SQL statement in [BSurfSpotDBOperations allSpots] \n %@ \n %@",sqlQuery,[NSString stringWithUTF8String:error]);

Format strings in NSLog() statements must be constant strings or there will be a warning. NSLog()语句中的格式字符串必须为常量字符串,否则将发出警告。 Re-write the code to make the format portion a string literal. 重新编写代码,使格式部分成为字符串文字。

In general avoid complex compound statements. 通常,避免使用复杂的复合语句。 Temporary variables make the code more readable and potentially less buggy. 临时变量使代码更具可读性,并且可能减少错误。 The compiler is quite good at elimination temporaries at release compile-time. 编译器在发布编译时非常擅长消除临时对象。

Example: 例:

const char* error; //it's set, not nil
NSString *errorString = [NSString stringWithUTF8String:error];
NSLog(@"Problem with SQL statement in [BSurfSpotDBOperations allSpots] \n %@ \n %@", sqlQuery, errorString);

stringWithFormat is unnecessary here since NSLog() gives you similar options. 由于NSLog()为您提供了类似的选项,因此在这里不需要stringWithFormat You could simply change it to this: 您可以将其更改为:

NSLog(@"Problem with ... \n %@ \n %@", sqlQuery,[NSString stringWithUTF8String:error]);

This will eliminate the warning since the NSLog knows it isn't going to run into a string literal it doesn't know what to do with, which is a security concern. 这将消除警告,因为NSLog知道它将不会遇到不知道该如何处理的字符串文字,这是安全问题。

Try this method : 试试这个方法:

NSLog([@"Problem with SQL statement in [BSurfSpotDBOperations allSpots] \n %@ \n %@"
,sqlQuery,[NSString stringWithUTF8String:error]);

I think you can also translate [NSString stringWithUTF8String:error] by error 我想你也可以翻译[NSString stringWithUTF8String:error]error

Think this can help you ;) 认为这可以帮助您;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM