Reputation: 63
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"
Upvotes: 3
Views: 297
Reputation: 122391
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?
Upvotes: 1
Reputation: 4268
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?
Upvotes: 3