Friday, May 16, 2014

Warning when using NSLog to log a single NSString as NSLog(str)

When using NSLog to log a single NSString parameter, if NSLog(nstringToLog) is used, a compiler warning of "Format string is not a string literal" will show. This warning message is not very clear, and many developer will just ignore it.

However, using NSLog in this way is quite danger, and may cause your app to crash at runtime, as the string parameter to be logged may contain %, which will be parsed as format place holder,  and at runtime, NSLog method will try to cast random memory address to the type specified by %. For example:
NSString* str = @"%i %@ %@";
NSLog(str);  //output is unpredictable and also may cause crash

The properly way of using NSLog to log a single NSString should be:
NSString* str = @"%i %@ %@";
NSLog(@"%@", str)
which will correctly log the string as "%i %@ %@"


No comments:

Post a Comment