Search code examples
objective-csearchnsset

Finding an object in NSSet of different objects


I have a NSSet that contains 3 different types of objects (FacebookGroup, Individual and NSMutableDictionary)

FacebookGroup and Individual are subclasses of NSManagedObject

Now I want to try to find an object matching key contactInfo so I do like this:

NSMutableDictionary *contactDict = [[self.contacts filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"contactInfo == %@", contactInfo]] anyObject];

if (contactDict) // the object is found

But FacebookGroups does not have the key contactInfo so an exception is throwed. I was hoping that instead an exception being throwed contactDict would be nil.

How can I search a NSSet of different objects without an exception being throwed?

* Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: the entity FacebookGroup is not key value coding-compliant for the key "contactInfo".'


Solution

  • The object you're searching for is a NSMutableDictionary, that's the way of recognizing it from other objects, sending a isKindOfClass message. So you should create a predicate that evaluates every object:

    NSPredicate* predicate= [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return [evaluatedObject isKindOfClass: [NSMutableDictionary class]];
    }];