简体   繁体   中英

Filter Array with dictionaries using NSPredicate

There is an Array with each element being a NSDictionary .

NSMutableArray *mutArr = [NSMutableArray array];

for (Person *person in persons) {
    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:person.name, @"name", person.email, @"email", nil];
    [mutArr addObject:dict];
}

self.arr = [[NSArray alloc] initWithArray:mutArr];

How to filer the arr with name or email contains string @"filter string" by using filterArrayUsingPredicate: method.

Thanks in advance!

Please see the below example:

 NSArray *array = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"filter string" forKey:@"email"]];   // you can also do same for Name key... 
    NSArray *filteredarray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(email == %@)", @"filter string"]];

Check this out :

var customerNameDict = ["firstName":"karthi","LastName":"alagu","MiddleName":"prabhu"];
var clientNameDict = ["firstName":"Selva","LastName":"kumar","MiddleName":"m"];
var employeeNameDict = ["firstName":"karthi","LastName":"prabhu","MiddleName":"kp"];

var attributeValue = "karthi";

var arrNames:Array = [customerNameDict,clientNameDict,employeeNameDict];

var namePredicate = NSPredicate(format: "firstName like %@",attributeValue);

let filteredArray = arrNames.filter { namePredicate.evaluateWithObject($0) };
println("names = ,\(filteredArray)");

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