tags:

views:

560

answers:

1

Hello,

I get the warning "Format not a string literal and no format arguments" on the NSLog call in the following block:

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

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

Thanks for any and all assistance!

Regards,

Steve O'Sullivan

+5  A: 

It's technically an invalid warning in your case, but it's telling you that your format string for NSLog is not hard-coded and could could be a security/stability issue. The fix is simple:

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

In case you're curious, what I mean by security/stability issue is this. In my example, the format string for NSLog is constant: @"%d", and you know when you compile it that NSLog will expect a single integer to be passed. When you call NSLog like NSLog([obj makeSomeString]), you don't really know at compile time what the format string is, or how many/which types of arguments should follow. If at run-time the string turns out to be "%d %d %@", it will happily read two integers and an NSObject from the stack, regardless of whether any objects were actually put there. That's the problem it's warning you of.

The warning is invalid in your case because the string you're generating has a format of %d, so it should never include the % character that would cause this problem to manifest.

alltom
well, "technically", the warning is actually valid! Being a dynamic language, it's possible to change the implementation of `stringWithFormat:` at runtime, so all the issues you mentioned could still happen.Also, you could change the string object to a problematic one, maybe by mistake, but the compiler can't check that; hence the warning.
Mo
Hm, true! Technically. :D
alltom