Sebastian
Sebastian

Reputation: 3399

How to use multiple NSPredicates for multiple search values

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) {
        NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {

        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:

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

But I don't get this result.

Upvotes: 2

Views: 1299

Answers (1)

LavaSlider
LavaSlider

Reputation: 2504

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]

Upvotes: 3

Related Questions