NSPredicate
を検索クエリに対して配列ivarの値をフィルタリングするにはどうすればよいですか?私は文字列ivarに対してNSPredicate
を使用することができます。私はAddressBookからユーザを作成するために使用される "ユーザ"という名前の1つのユーザ定義クラスを持っています。ここに私のコードですiphoneのNSArrayに対するNSPredicate
// User Defined Class named as "User"
// In User.h
@interface User : NSObject {
NSString *firstName;
NSString *lastName;
NSString *company;
UIImage *userImage;
NSArray *phoneNumberArray;
NSArray *emailArray;
NSArray *urlArray;
NSArray *addressArray;
NSString *notes;
NSString *dateOfBirth;
}
// In SearchViewController.m
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
// contactsArray is NSMutableArray
contactsArray = [Search searchContactsWithQuery:searchText];
NSLog(@"contactsArray count => %d",[contactsArray count]);
[contactsTableView reloadData];
}
// In Search.m
+(NSMutableArray*)searchContactsWithQuery:(NSString*)query {
NSLog(@"Query => %@",query);
NSMutableArray* predicates=[[NSMutableArray alloc] init];
// Create all predicates
NSPredicate * firstNamePredicate = [NSPredicate predicateWithFormat:@"firstName contains %@",query];
[predicates addObject:firstNamePredicate];
NSPredicate * lastNamePredicate = [NSPredicate predicateWithFormat:@"lastName contains %@",query];
[predicates addObject:lastNamePredicate];
NSPredicate * companyPredicate = [NSPredicate predicateWithFormat:@"company contains %@",query];
[predicates addObject:companyPredicate];
// Don't know how to use on array
// === START of ARRAY Predicate ====
NSPredicate *phoneNoPredicate = [NSPredicate predicateWithFormat:@"phoneNumberArray IN %@",query];
[predicates addObject:phoneNoPredicate];
NSPredicate *emailPredicate = [NSPredicate predicateWithFormat:@"emailArray contains %@",query];
[predicates addObject:emailPredicate];
NSPredicate *urlPredicate = [NSPredicate predicateWithFormat:@"urlArray contains %@",query];
[predicates addObject:urlPredicate];
NSPredicate *addressPredicate = [NSPredicate predicateWithFormat:@"addressArray contains %@",query];
// === END of ARRAY Predicate ====
NSPredicate *notesPredicate = [NSPredicate predicateWithFormat:@"notes contains %@",query];
[predicates addObject:notesPredicate];
NSPredicate *dobPredicate = [NSPredicate predicateWithFormat:@"dateOfBirth contains %@",query];
[predicates addObject:dobPredicate];
// Add predicates to array
NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:predicates];
NSArray * filteredArray = [APP_DELEGATE.allUsersArray filteredArrayUsingPredicate:compoundPredicate];
return [NSMutableArray arrayWithArray:filteredArray];
}
phoneNumberArray、emailArray、urlArray &ユーザーがなど他のノー電話、電子メール、アドレス、自宅、職場、iPhoneのようなURL、
方法のための複数のエントリを持っている可能性があるためaddressArrayが使用されています私は配列の述語を使うことができますか?どんな種類の助けにも感謝します。ありがとう
'filteredArrayUsingPredicate:'は正しい方法です。上記のコードは機能していませんか?述語と一致する値が配列に存在することは確かですか? – Caleb
配列に、述語 – iOSAppDev
と一致する値があります。述語を簡略化してみてください。複合述語を使用する代わりに、簡単な述語の1つを使用して配列をフィルタリングしてみてください。確かに、あなたは9つの別々の配列を得るためにそれぞれを適用することができます - それはあなたに問題がどこにあるのかの手がかりを与えるかもしれません。 – Caleb