Reputation: 4496
The task:
Return an object from an NSArray
that's instance of the class who's name is given as parameter to the function.
Right now I have this function:
+ (id)objectOfType:(NSString *)name fromArray:(NSArray *)array
{
for (NSObject* instance in array)
{
if ([instance.className isEqualToString:name])
return instance;
}
return nil;
}
However, given that I can transform an array of objects into an array of class names of the objects with this simple method call on an NSArray
[array valueForKeyPath:@"className"]
shouldn't there also be a more concise way to retrieve the object with the specified class name..?
Upvotes: 0
Views: 371
Reputation: 7552
Here is a concise method, using NSPredicate
and array filtering.
+ (id)objectOfType:(NSString *)name fromArray:(NSArray *)array {
return [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"class == %@", NSClassFromString(name)]].lastObject;
}
Upvotes: 1