Question

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".'

Was it helpful?

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]];
}];

OTHER TIPS

If you create your predicate using + (NSPredicate *)predicateWithBlock:(BOOL (^)(id evaluatedObject, NSDictionary *bindings))block then you can perform a check in the block to ensure that the evaluatedObject has the key and then perform the appropriate check.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top