Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do I do: [obj isKindOfClass:[Class class]]

The task looks to be simple: to check if element is of type Class, but I don't get how. What I have is an array with different data. For example:

NSArray *arr = @[@"name", [NSArray class]];
NSLog(@"type:%@", [arr elementByClass:[Class class]]); //expecting here "type:NSArray"

I need to get first element with custom class. So here's my NSArray category method:

- (id)elementByClass:(Class)elementClass {
    for (id obj in self) {
        if([obj isKindOfClass:elementClass]){
            return obj;
        }
    }
    return nil;
}

though it doesn't compile and fails with error:

"receiver type 'Class' is not an Objective-C class"

like image 688
Vladimir Avatar asked Feb 07 '26 11:02

Vladimir


1 Answers

Actually, the Class itself is not an Objective-C object. If you really want to do what you are trying to do, through, you can:

#import <objc/runtime.h>

- (void)doSomething {
    NSArray *arr = @[@"name", [NSArray class]];
    NSLog(@"type:%@", [arr elementByClass:objc_getMetaClass("NSObject")]); //expecting here "type:NSArray"
}

I would suggest answer to next question as a further reading: Are classes objects in Objective-C?

like image 84
Borys Verebskyi Avatar answered Feb 08 '26 23:02

Borys Verebskyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!