3

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"

Vladimir
  • 63
  • 8

2 Answers2

3

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?

Community
  • 1
  • 1
Borys Verebskyi
  • 4,160
  • 6
  • 28
  • 42
1

You should be able to check if [obj class] is the exact same instance of the elementClass you are looking for:

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

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

Community
  • 1
  • 1
trojanfoe
  • 120,358
  • 21
  • 212
  • 242