我想根据不同的标准从nsdictionary搜索数据。我有4个密钥,用户可以根据任意数量的密钥进行搜索ex:4,3 etc..Ex:我有包含密钥的字典(名字,最后姓名,地址,电话号码。。现在用户可以根据任何键搜索名字和姓氏,或只有名字。我正在使用NSPredicate搜索。我的问题是如何创建动态nspredicate?如果我提供空字符串
[NSPredicate predicateWithFormat:@"FirstName CONTAINS[cd] %@ AND LastNAme CONTAINS[cd] %@ AND Address CONTAINS[cd] %@ AND PhoneNumber CONTAINS[cd] %@",firstname,lastname,addr,phone]
它没有给出任何结果。我怎么能实现这个?或者我必须根据用户提供的字段创建多个nspredicate?
提前致谢!
答案 0 :(得分:2)
您可以通过编程方式构建谓词:
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];
然后使用filter
过滤您的词典。