Search code examples
objective-cruntime-errornslog

NSLog gives runtime error


Ok, so I know I can just leave out the NSLog but why does it give me a "EXC_BAD_ACCESS" error?

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex2
{

    if(buttonIndex2 == 0 && waitForAction == NO)
    {
        waitForAction = YES;
        [self showAbortAlert];
        NSLog(@"%@",buttonIndex2); //This one does not crash the app

    } else if (buttonIndex2 == 1 && waitForAction == NO)
    {
        waitForAction = YES;
        [self addObject];
        NSLog(@"%@",buttonIndex2); //This one crashes the app
    } //else if
}

Solution

  • see the method signature again

    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex2
    

    buttonIndex2 is of type NSInteger. If you do %@ in NSLog your code is calling the description method on the object. But buttonIndex2 is not an object.

    use NSLog(@"%d",buttonIndex2);

    The first one (with buttonIndex == 0) does not crash the app because you are calling description on an object at memory address 0, which is basically the same as [nil description] and this is perfectly legal in Objective-C.