2014-02-06 60 views
-1

我试图使用NSPredicate来过滤NSDictionary。似乎有一个错误。使用nspredicate进行Nsdictionary过滤

我有这个NSDictionary

dict = [[NSDictionary alloc] initWithObjectsAndKeys:translation, @"trans", meaning, @"mean", pronounce, @"pron", theId, @"id", nil]; 

我要筛选本字典。如果在字典中id键的值等于passedId,将其添加到NSArray

我用下面的代码:

NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"theId == %@", passedId]; 
NSArray *requiredRows = [[dict allKeys] filteredArrayUsingPredicate:filterPredicate]; 

给了我这个错误:

'NSUnknownKeyException', reason: '[<__NSCFConstantString 0xada8> valueForUndefinedKey:]: this class is not key value coding-compliant for the key theId. 
+0

@iMani,第一行代码呢? – vikingosegundo

回答

0

你的钥匙是id

theId, @"id", 

所以你的谓词使用了错误的键。它应该是:

[NSPredicate predicateWithFormat:@"id == %@", passedId] 

因为字典和谓词中的键必须匹配。


我原本没有注意到您使用[dict allKeys]。这会从一个字典中获得所有密钥的数组。这里没有任何值,没有点过滤它。

您应该有一个字典数组,并在该数组上运行谓词。然后结果将只包含匹配id的字典。

+0

此类不是密钥编码兼容的密钥ID。 – user3258468

0

你的代码根本没有意义。将它分成多行,使之明显:

NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"theId == %@", passedId]; 
NSArray *allKeys = [dict allKeys]; 
NSArray *requiredRows = [allKeys filteredArrayUsingPredicate:filterPredicate]; 

allKeys是NSString的数组,它看起来像这样@"id", @"mean", @"pron", @"trans"。您无法过滤@"theId",因为对于每个NSString,过滤基本上都会调用[NSString theId],并且此方法的结果将与您在谓词中指定的字符串进行比较。这是异常来自的地方,NSString没有名为theId的方法。

即使这样做会工作,因为您使用self == %@作为谓词,您将返回的唯一结果将是@"theId"

我不确定你真正想要什么,但它不会像这样工作。