简体   繁体   中英

ios using NSPredicate to filter content crash if the result is null

I have array of dictionaries like this:

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

Where if I use NSPredicate to find the clients in USA like this:

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

works just fine but if for some reason the result of the predicte is null for example in this case:

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

I get this error:

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

Any of you knows why or how can avoid having this error when the predicate is empty or null?

I'll really appreciate your help

try this

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

NSArray *filteredArray = [listOfClients filteredArrayUsingPredicate:predicate];

Assuming filterArray always have count 1.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM