[英]Objective-C: NSPredicate Check Two Arrays
現在,我有一個正在運行的應用程序(類似於WhatsApp),用戶可以使用NSTextField進行實時搜索以將用戶添加到群聊中。 使用NSPredicate,我搜索了一個數組(searchableContacts)以找到應用程序上任何可用的聯系人,並且像匹配項一樣輸出到UITableView中,如下所示:
- (void)textFieldDidChange :(UITextField *)theTextField {
[filteredArray removeAllObjects];
NSMutableArray *partPredicates = [NSMutableArray arrayWithCapacity:2];
NSPredicate *currentPartPredicate1 = [NSPredicate predicateWithFormat:@"firstName CONTAINS[cd] %@", self.searchField.text];
NSPredicate *currentPartPredicate2 = [NSPredicate predicateWithFormat:@"lastName CONTAINS[cd] %@", self.searchField.text];
[partPredicates addObject:currentPartPredicate1];
[partPredicates addObject:currentPartPredicate2];
NSPredicate *fullPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:partPredicates];
filteredArray = [[self.searchableContacts filteredArrayUsingPredicate:fullPredicate] mutableCopy];
[self.searchableMembers reloadData];
}
在生成的tableView上,用戶可以選擇要添加到組中的用戶。 現在,我有一個“ addedContacts”數組。
當用戶返回到textField中以搜索更多要添加到該組的用戶時,如何更改我的NSPredicate以包括該組中尚未存在的可用聯系人(來自searchableContacts)(添加的Contacts)?
您可以簡化構建謂詞所需的代碼:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstName CONTAINS[cd] %@ OR lastName CONTAINS[cd] %@", self.searchField.text, self.searchField.text];
您可以使用以下方法進行調整,以排除添加的addedContacts
的項目:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(NOT SELF IN %@) AND (firstName CONTAINS[cd] %@ OR lastName CONTAINS[cd] %@)", self.addedContacts, self.searchField.text, self.searchField.text];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.