William Falcon
William Falcon

Reputation: 9823

NSPredicate using OR error

First time building an NSPredicate.

I would like to search a managedobjectcontext using this logic:

Search for a, grab all matches
Search for b, grab all matches, etc....

Nsarray *results = (has all a results, b results, etc);

My attempted predicate is:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name== %@ OR name == %@ OR name == %@",a,b,c];

However I get errors with this predicate...

Edited: Sample method I wrote

-(NSPredicate*)parsePartsIntoAPredicate:(NSMutableArray*)inputPartsNames{
    NSSet *keys=[NSSet setWithArray:inputPartsNames];
    NSPredicate *predicate=[NSPredicate predicateWithFormat:@"any self.@name in %@", keys];
    NSLog(@"predicate = %@",predicate);
    return predicate;
}

Clarify: I have a database of cars (20,000) Each car has multiple parts. I want to find all cars that have part a, and all cars that have part b, and all that have part c. Then I want to return an array with cars with part a, b, c, etc...

If you think there is a better way let me know, but I am approaching this backwards. I am saying

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Cars" inManagedObjectContext:[self managedObjectContext]];
    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate:[self parsePartsIntoAPredicate:inputParts]];

    NSError *error;
    NSArray *records = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];

What am I doing wrong?

Upvotes: 1

Views: 194

Answers (3)

Martin R
Martin R

Reputation: 540075

To fetch all Cars objects that have a name which is one of the strings in the keys set or array, use

[NSPredicate predicateWithFormat:@"name IN %@", keys]

Upvotes: 0

Vishal
Vishal

Reputation: 556

Use this

NSPredicate* predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ '%@'", @"SELF contains[c] ",searchText]];

Upvotes: 2

Manu
Manu

Reputation: 4750

NSString *key;
NSMutableArray *tempArray;
NSPredicate *searchForName = [NSPredicate predicateWithFormat:@"name = %@", key];
NSArray *filterArray = [tempArray filteredArrayUsingPredicate:searchForName];
NSLog(@"%@",filterArray);

Where key is your searchKeyword, tempArray is your CompleteArray in which data is present.

Use Like this. Please put your data.

Upvotes: 2

Related Questions