【问题标题】:NSString stringWithFormat format warningNSString stringWithFormat 格式警告
【发布时间】:2014-06-06 20:02:29
【问题描述】:

我可能使用了错误的符号来将 NSString 类型包含在另一个字符串中。

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

表达式有效,但我收到以下警告:

Formatting string is not a string literal(potentially insecure)

有没有办法摆脱警告?

【问题讨论】:

  • 刚刚发布的代码缺少尾随“]”。一如既往地分解复合语句,尤其是在调试时。 NSLog() 在每一步之后或使用调试器在每一步之后进行检查。;
  • 您在NSLog() 中有完整的声明吗?
  • 是的,它在 NSLog 中,查看编辑
  • 摆脱stringWithFormat:both使用,并使用%s而不是%@作为error

标签: ios nsstring


【解决方案1】:

根据NSLog 实现,该函数需要一个常量字符串或格式说明符字符串作为它的第一个参数。

你需要使用:

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

【讨论】:

    【解决方案2】:

    NSLog() 语句中的格式字符串必须是常量字符串,否则会出现警告。重新编写代码以使格式部分成为字符串文字。

    通常避免复杂的复合语句。临时变量使代码更具可读性并且可能更少错误。编译器非常擅长在发布编译时消除临时变量。

    例子:

    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);
    

    【讨论】:

    • 更好——去掉errorString,使用%s直接登录error。不需要NSString
    • 从调试 POV 中,额外的语句可能会暴露错误,可能它没有真正设置,没有以 null 终止等。请注意,错误语句不包含在原始问题中。通常在调试时存在不正确的假设,验证每个步骤有助于揭露不正确的假设。
    【解决方案3】:

    stringWithFormat 在这里是不必要的,因为NSLog() 为您提供了类似的选项。您可以简单地将其更改为:

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

    这将消除警告,因为 NSLog 知道它不会遇到它不知道如何处理的字符串文字,这是一个安全问题。

    【讨论】:

      【解决方案4】:

      试试这个方法:

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

      我想你也可以把[NSString stringWithUTF8String:error]翻译成error

      认为这可以帮助你;)

      【讨论】:

        猜你喜欢
        • 2012-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多