Check if object is Class type

后端 未结 5 1917

I have a method that receives a NSArray of Class objects and I need to check if they all are Class type generated with the code bellow

5条回答
  •  孤街浪徒
    2020-12-02 10:47

    To determine if an "object" is a class or an instance you need to check if it is a meta class in a two stage process. First call object_getClass then check if it is a meta class using class_isMetaClass. You will need to #import .

    NSObject *object = [[NSObject alloc] init];
    Class class = [NSObject class];
    
    BOOL yup = class_isMetaClass(object_getClass(class));
    BOOL nope = class_isMetaClass(object_getClass(object));
    

    Both Class and *id have the same struct layout (Class isa), therefore can pose as objects and can both receive messages making it hard to determine which is which. This seems to be the only way I was able to get consistent results.

    EDIT:

    Here is your original example with the check:

    NSMutableArray *arr = [[NSMutableArray alloc] init];
    
    [arr addObject:[NSObject class]];
    [arr addObject:[NSValue class]];
    [arr addObject:[NSNumber class]];
    [arr addObject:[NSPredicate class]];
    [arr addObject:@"not a class object"];
    
    for (int i; i<[arr count]; i++) {
        id obj = [arr objectAtIndex:i];
    
        if(class_isMetaClass(object_getClass(obj)))
        {
            //do sth
            NSLog(@"Class: %@", obj);
        }
        else
        {
            NSLog(@"Instance: %@", obj);
        }
    }
    
    [arr release];
    

    And the output:

    Class: NSObject
    Class: NSValue
    Class: NSNumber
    Class: NSPredicate
    Instance: not a class object

提交回复
热议问题