开发者

How to filter nsdictionary?

开发者 https://www.devze.com 2023-04-09 04:17 出处:网络
I want to search data from nsdictionary based on different criteria.Say I have 4 keys and user can search based on any number of keys ex:4,3 etc..Ex:I have dictionary containing keys(First Name,Last N

I want to search data from nsdictionary based on different criteria.Say I have 4 keys and user can search based on any number of keys ex:4,3 etc..Ex:I have dictionary containing keys(First Name,Last Name,Address,Phone Number).Now user can search based on any key say First Name and Last Name, or only First Name.I am using NSPredicate to search.My problem is how to create dynamic nspredicate?If I provide empty string in

[NSPredicate predicateWithFormat:@"FirstName  CONTAINS[cd] %@ AND LastNAme  CONTAINS[cd] %@ AND Address  CONTAINS[cd] %@ AND PhoneNumber  CONTAINS[cd] %@",firstname,lastname,addr,phone]

It does not give any result.How can I achieve this?or I have to create multiple nspredicate based on fields use开发者_JS百科r has provide?

Thanks in advance!


You can build the predicate programmatically:

NSArray *keysToSearch = [NSArray arrayWithObjects:@"FirstName", @"LastName", @"Address", nil];
NSString *searchString = @"Bob";

NSMutableArray *subPredicates = [NSMutableArray array];
for (NSString *key in keysToSearch) {
  NSPredicate *p = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", key, searchString];
  [subPredicates addObject:];
}

NSPredicate *filter = [NSCompoundPredicate andPredicateWithSubPredicates:subPredicates];

Then use filter to filter your dictionaries.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号