解決編譯時出現的警告:format string is not a string literal (potentially insecure)┊
在Xcode 4.2(iOS 5)之前,我猜大家都和我一樣很喜歡下面的除錯輸出寫法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
NSString *str = @ "Attention" ;
// first warning
NSLog (str);
// second warning
NSLog ([str stringByAppendingFormat:@ ", %@" , @ "Xcode 4.2 do not support this format!" ]);
// third warning
NSLog ([ NSString stringWithFormat:@ "%@, Xcode 4.2 do not support this format!" , @ "Attention" ]);
// fourth warning
NSException *exception = [ NSException exceptionWithName:@ "Attention"
reason:@ "Xcode 4.2 do not support this format!"
userInfo: nil ];
NSLog (exception);
|
但是在Xcode 4.2(iOS 5)之後,貌似蘋果更新的編譯器,出了支援ARC的Apple LLVM compiler 3.0。然後我發現每次編譯,以前的這些輸出都會產生一個warning(警告,黃色三角形)。
在StackOverflow和iPhone Dev SDK查詢相關答案之後,發現在最新版的編譯器裡面NSLog為了安全,只接受格式化的字串,因為NSLog底層也是用printf來格式化輸出的。
所以上面的寫法都會給出警告,可以把上面的寫法修改為以下合法模式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
NSString *str = @ "Attention" ;
// first warning
NSLog (str); // warning
NSLog (@ "%@" , str); // solution
NSLog (str, nil ); // solution
// second warning
NSLog ([str stringByAppendingFormat:@ ", %@" , @ "Xcode 4.2 do not support this format!" ]); // warning
NSLog (@ "%@" , [str stringByAppendingFormat:@ ", %@" , @ "Xcode 4.2 do not support this format!" ]); // solution
NSLog ([str stringByAppendingFormat:@ ", %@" , @ "Xcode 4.2 do not support this format!" ], nil ); //solution
// third warning
NSLog ([ NSString stringWithFormat:@ "%@, Xcode 4.2 do not support this format!" , @ "Attention" ]); // warning
NSLog (@ "%@, Xcode 4.2 do not support this format!" , @ "Attention" ); // solution
NSLog ([ NSString stringWithFormat:@
|