Search NSArray using NSPredicate - iphone

I am new to NSPredicate so sorry if I am asking stupid question. I have two NSArray (keyArray and valueArray). I have to find match in valueArray using keyArray. Below code is working fine but I have to search one by one. Any way to search an array using a different key array.
NSPredicate *userPredicate = [NSPredicate predicateWithFormat:#"companyId = %#", [[[self selectedCompanies] objectAtIndex:0] companiesIdentifier]];
NSLog(#"Users: %#", [[[self userData] users] filteredArrayUsingPredicate:userPredicate]);
NSPredicate *userPredicate1 = [NSPredicate predicateWithFormat:#"companyId = %#", [[[self selectedCompanies] objectAtIndex:1] companiesIdentifier]];
NSLog(#"Users: %#", [[[self userData] users] filteredArrayUsingPredicate:userPredicate1]);

You can do:
NSPredicate *userPredicate1 = [NSPredicate predicateWithFormat:#"companyId IN %#", [[self selectedCompanies] valueForKey:#"companiesIdentifier"];
NSLog(#"Users: %#", [[[self userData] users] filteredArrayUsingPredicate:userPredicate1]);
What happens here is we take the companiesIdentifier of all selected companies and match users based on those identifiers.
valueForKey: on an array object returns an array with the value of the required key for each object in the array. IN is a predicate operator searching in a collection (array, set, etc.).

Related

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?
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.
Use this
NSPredicate* predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"%# '%#'", #"SELF contains[c] ",searchText]];
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]

Predicate in array

I have an array which contains lots of info like lat,lon,city name etc.But all this info stored by class object.
("<GetCityList: 0x1fd334d0>",
"<GetCityList: 0x1fd33560>",
"<GetCityList: 0x1fd33310>",)
my array is looking like this.if i want city name then first i create GetCityList object and then object.cityName.
Now i have to search lat and lon by comparing cityName.so how can i do,because it consumes too much time?can i use predicate ?how?
Let say you have an array of cityList and want to Filter this by city name you can do
NSPredicate *cityNamePredicate = [NSPredicate predicateWithFormat:#"cityName contains[c] %#", #"cityName"]
NSArray *filteredCityList = [cityList filteredArrayUsingPredicate:cityNamePredicate];
Above filteredCityList will be your required filtered array whatever you passed in parameter. Here [cd] means case and diatric insensitive
You can refer this tutorial for further exploring NSPredicate.
Example:
self.data = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"To Airport",#"TO/AIR", nil] forKeys:[NSArray arrayWithObjects:kName,kCode, nil]],
[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"Point-to-Point",#"PTP", nil] forKeys:[NSArray arrayWithObjects:kName,kCode, nil]],[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"From Airport",#"FR/AIR", nil] forKeys:[NSArray arrayWithObjects:kName,kCode, nil]], nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(name CONTAINS[cd] %#)",searchText];
self.searchableData = [self.data filteredArrayUsingPredicate:predicate];
Based on this you can replace name with cityName.
Use it in this way also:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"cityName contains %#", #"cityNamehere"]
NSMutableArray *filtered = [cityListArray filterUsingPredicate:predicate];

Filtering NSArray of NSDictionary objects using NSPredicate

I have an NSArray of NSDictionary objects. I want to filter the array based on keys of the dictionaries using NSPredicate. I have been doing something like this:
NSString *predicateString = [NSString stringWithFormat:#"%# == '%#'", key, value];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
NSArray *filteredResults = [allResultsArray filteredArrayUsingPredicate:predicate];
This works fine if they key passed in is one-word: Color, Name, Age. But it doesn't work if the key is multi-word, like: Person Age, Person Name.
Basically, any key that contains a space, it doesn't work. I have tried putting single quotes around the key in the string, just like they are done on the value side but that didn't work either. Also tried double quotes, but to no avail.
Please advise on this. Thanks in advance.
For me, Kevin's answer did not work. I used:
NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"%K contains[cd] %#", keySelected, text];//keySelected is NSString itself
NSLog(#"predicate %#",predicateString);
filteredArray = [NSMutableArray arrayWithArray:[YourArrayNeedToFilter filteredArrayUsingPredicate:predicateString]];
When using a dynamic key, you should use the %K token instead of %#. You also don't want the quotes around the value token. They will cause your predicate to test for equality against the literal string #"%#" instead of against value.
NSString *predicateString = [NSString stringWithFormat:#"%K == %#", key, value];
This is documented in the Predicate Format String Syntax guide.
Edit: As Anum Amin points out, +[NSString stringWithFormat:] doesn't handle predicate formats. You want [NSPredicate predicateWithFormat:#"%K == %#", key, value] instead.

NSPredicate filter

I have never used NSPredicate before so please bear with me. I have an array which have a boolean key as "isChecked". I want to filter the array which have the boolean set as "YES", any idea how can I do it, plus if there is any reference to such query methods that would be nice to have it handy.
Thanks
//NSArray * myArray is your array
//containing your objects that each have an isChecked property
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"isChecked == YES"];
NSArray *filteredArray = [myArray filteredArrayUsingPredicate:predicate];
// filteredArray is the new array that only contains your checked items
Cheers
First you create an NSPredicate instance. In this case, we'll use -initWithFormat:.
NSPredicate *predicate = [[NSPredicate alloc] initWithFormat:#"isChecked == YES"];
Then we'll use the -filteredArrayUsingPredicate: method on NSArray to get an NSArray of all the objects which match the predicate.
NSArray *filteredArray = [originalArray filteredArrayUsingPredicate:predicate];

Use NSPredicate to filter by object attribute

I have a mutable array of custom objects. I want to filter that array by attribute of the object, for example myObject.attributeOne.
How can I create the NSPredicate to use with
[myArrayOfObjects filterUsingPredicate:<the_predicate>]
Use it in this way:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"FriendStatus == 1"];
NSMutableArray *filtered = [MessageArray filteredArrayUsingPredicate:predicate];