如果结果为null,则使用NSPredicate来过滤内容崩溃

时间:2013-10-16 19:15:59

标签: iphone ios objective-c xcode nspredicate

我有这样的字典数组:

clients (
        {
        country = canada;
        city = vancouver;
    },
{
        country = Mexico;
        city = Mexico;
    },
{
        country = UK;
        city = London;
    },
{
        country = USA;
        city = NewYork;
    },
}

如果我使用NSPredicate在美国找到这样的客户:

NSPredicate *usaPredicte = [NSPredicate predicateWithFormat:@"SELF contains %@", @"USA"];
self.usa = [listOfClients filteredArrayUsingPredicate:usaPredicte];

工作正常,但如果由于某种原因,谓词的结果为null,例如在这种情况下:

NSPredicate *peruPredicte = [NSPredicate predicateWithFormat:@"SELF contains %@", @"Peru"];
self.peru = [listOfClients filteredArrayUsingPredicate:peruPredicte];

我收到此错误:

-[__NSCFDictionary filteredArrayUsingPredicate:]: unrecognized selector sent to instance 0xdcb6e0

当谓词为空或为空时,你们中的任何人都知道为什么或如何避免出现此错误?

我真的很感谢你的帮助

1 个答案:

答案 0 :(得分:0)

试试这个

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(country ==  %@)", @"USA"];

NSArray *filteredArray = [listOfClients filteredArrayUsingPredicate:predicate];

假设filterArray总是有计数1。

if (filteredArray.count ) 
     self.usa = [[filteredArray objectAtIndex: 0] objectForKey: @"country"];