Take the 2-minute tour ×

I'm using a UITextField as a search field: The user can input multiple search values separated by comma. By typing I want to find every custom object in my NSArray that matches one of the search component.

My custom objects have no properties (that can be used for the search). Receiving a value I have to call [myObject fieldForKey:@"username"].value;. Because of this I have to use [NSPredicate predicateWithBlock] (or another way was not possible for me).

My method for the search (will be called whenever a character was changed in the TextField):

-(void)searchEntriesWithString:(NSString*)searchString {
    NSArray *dataSource = [NSArray arrayWithArray:_allObjects];

    searchString = [searchString stringByReplacingOccurrencesOfString:@" " withString:@""];

    NSArray *components = [searchString componentsSeparatedByString:@","];
    NSMutableArray *predicates = [NSMutableArray array];
    for (NSString *value in components) {

        return ( [[(MyObject*)evaluatedObject fieldForKey:@"username"].wert hasPrefix:value ]);

        [predicates addObject:predicate];

        NSPredicate *resultPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];

    NSMutableArray searchResultArray = [NSMutableArray arrayWithArray:[dataSource filteredArrayUsingPredicate:resultPredicate]];

Assuming following dataSource:

  • Object1 with username "userA"
  • Object2 with username "userB"
  • Object3 with username "userC"

Calling the method with '[self searchEntriesWithString:@"userA,userB"]' should result in an array with Object1 and Object2.

But I don't get this result.

share|improve this question
Maybe it isn't possible this way with NSPredicate? I removed the NSPredicate usage and use normal for loops. My App works now, but I'm still wondering why my code with NSPredicate isn't working. –  Sebastian Mar 4 '13 at 14:52
add comment

1 Answer

up vote 2 down vote accepted

Since you wanted one of the search components, not all of the search components, I think you should have used:

NSPredicate *resultPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:predicates];

As you had it using andPredicateWithSubpredicates a term would have needed to pass for "userA" and "userB".

[I realize you asked this three months ago, have found a work around, and moved on but thought I would just leave a suggestion]

share|improve this answer
I tested your suggestion and it's working. Thanks for your help! –  Sebastian May 24 '13 at 18:22
You're welcome... I've experienced the frustration of trying to get an NSPredicate to do what I want it to do. –  LavaSlider May 25 '13 at 12:21
add comment

Your Answer


