Search code examples
objective-c

Objective-C "Messaging unqualified id" when trying to determine type of class from id


I'm getting the following compiler warning when trying to determine the type of an object passed in:

Messaging unqualified id

This is a simplification of a situation in a large prod codebase:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [ViewController myMethod:@"MyString"];
    
    [ViewController myMethod:@[@(1), @(2), @(3)]];
    
    [ViewController myMethod:@(13)];
}

+ (void)myMethod:(id)authenticationData {
    if ([authenticationData isKindOfClass:[NSArray class]]) { // ERROR: Messaging unqualified id
        NSLog(@"NSArray");
    } else if ([authenticationData isKindOfClass:[NSString class]]) { // No error here because the compiler stops checking after the first one. If above statement is commented out --> same error here
        NSLog(@"NSString");
    } else {
        NSLog(@"Unknown");
    }
}

@end

Solution

  • The warning is caused by -Wobjc-messaging-id in your project. The flag is pretty much optional (and for all of my projects it is disabled by default), so you can just disable it if you need an id object being invocable without compiler analysis.

    If for whatever reason you cannot afford disabling the flag, you are supposed to make the object interface apparent to the compiler (so it can see the method of the object you invoke it with). Since isKindOfClass: belongs to NSObject protocol it's the minimal typing you are required to introduce for your authenticationData parameter to get rid of the warning:

    + (void)myMethod:(id<NSObject>)authenticationData