Search code examples
objective-ccocoaexc-bad-access

isKindOfClass on id object causes EXC_BAD_ACCESS


Why I tried to use isKindOfClass on an id object. Sometimes, it went wrong badly and shows EXC_BAD_ACCESS

Here is the code (will be called when user clicked on Growl notification):

- (void)growlNotificationWasClicked:(id)fromUserClick {
    NSDictionary *data = (NSDictionary *)fromUserClick;
    id object = [[data objectForKey:@"someKey"] unsignedLongValue];

    if([object isKindOfClass:[NSNumber class]]) {
        NSLog(@"test");
    }
}

And here is what inspector showed during the crash:

enter image description here

Please help me on this issue. Thank you.


Solution

  • isKindOfClass is a method of NSObject. When you use unsignedLongValue, it returns an unsigned long and unsigned long isn't an object.

    That's why you got crash.

    P/S: When you write [[data objectForKey:@"someKey"] unsignedLongValue], it always return a number. You don't need to check the returned value is a number or not. Just use it.

    unsigned long number = [[data objectForKey:@"someKey"] unsignedLongValue];