0

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..?

3
  • Depends on what you want to do. An array is a sorted list and the current implementation is returning the first match. There could of course be more. It could be done based on sets with a predicate filter but that would return a subset or subarray of all matches. Are you always looking for the first match or all? Commented Feb 14, 2016 at 8:41
  • Any match at all (as in the code sample) would do - cheers Commented Feb 14, 2016 at 10:10
  • 1
    In that case I think your implementation is fit for purpose. I think creating and parsing predicates is most likely far slower than the above approach, at least for reasonably sized arrays (a few hundred objects). Commented Feb 14, 2016 at 10:22

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I guess that'll make for a nice category solving the task in a pretty concise way - cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.