如何过滤nsdictionary?

发布于 2024-12-07 06:24:47 字数 475 浏览 0 评论 0原文

我想根据不同的条件从 nsdictionary 中搜索数据。假设我有 4 个键,用户可以根据任意数量的键进行搜索,例如:4,3 等。例如:我有包含键的字典(名字、姓氏、地址) ,电话号码)。现在用户可以根据任何键(如名字和姓氏,或仅名字)进行搜索。我正在使用 NSPredicate 进行搜索。我的问题是如何创建动态 nspredicate?如果我在中提供空字符串,

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

则不会给任何结果。我怎样才能实现这个?或者我必须根据用户提供的字段创建多个 nspredicate?

提前致谢!

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 user has provide?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风筝有风,海豚有海 2024-12-14 06:24:47

您可以通过编程方式构建谓词:

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 来过滤您的字典。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文