I get the warning “Format is not a string literal and format arguments” in NSLog - how can I fix this in code?

I get the warning “Format is not a string literal and format arguments” in an NSLog call in the following block:

 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSLog([NSString stringWithFormat:@"%d", buttonIndex]); } 

I read in another post here that this error message indicates an unsafe use of NSLog . Can someone point me in the direction of a properly formatted string for this?

+6
cocoa
source share
1 answer

This is a technically invalid warning in your case, but it tells you that your format string for NSLog is not hardcoded and may be a security / stability issue. The fix is ​​simple:

 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSLog(@"%d", buttonIndex); } 

If you're interested, I mean the security / stability issue. In my example, the format string for NSLog is constant: @"%d" , and you know, when you compile it, that NSLog expects a single integer to be transmitted. When you call NSLog as NSLog([obj makeSomeString]) , you do not know at compile time what the format string is, or how many / what types of arguments to follow. If at run time the string appears to be "%d %d %@" , it will happily read two integers and an NSObject from the stack, regardless of whether any objects were actually placed there. This is the issue you are warning about.

The warning is not valid in your case, because the line you create is in the format% d, so it should never include the % character, which may cause this problem.

+11
source share

All Articles