0

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

4

2 回答 2

0

如果您使用+ (NSPredicate *)predicateWithBlock:(BOOL (^)(id evaluatedObject, NSDictionary *bindings))blockthen 创建谓词,则可以在块中执行检查以确保evaluatedObject具有键,然后执行适当的检查。

于 2013-06-24T11:59:25.843 回答
0

您正在搜索的对象是NSMutableDictionary,这是从其他对象中识别它的方式,发送isKindOfClass消息。因此,您应该创建一个评估每个对象的谓词:

NSPredicate* predicate= [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    return [evaluatedObject isKindOfClass: [NSMutableDictionary class]];
}];
于 2013-06-24T12:06:10.267 回答