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 %@ %@"


1 comment:

  1. Your blogs are authentic. I love them .Are you also searching for essay help? we are the best solution for you. We are best known for delivering quality essay help.

    ReplyDelete