NSPredicate filter - iphone

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];

Related

Search NSArray using NSPredicate

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.).

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]

How to use searchDisplayController with objects of class

I have a class, with some objects (Title, price, modifier), And I have an NSArray of objects of this class.
I load this NSArray into UITableView. How can I use searchDisplayController?
I can't understand.. array have only addresses (to objects in my class) and how i can sort it by predicate?
I can explain with an example
Let consider my code is like below
Without NSPredicate
NSMutableArray *oldSkoolFiltered = [[NSMutableArray alloc] init];
for (Book *book in bookshelf) {
if ([book.publisher isEqualToString:#"Apress"]) {
[oldSkoolFiltered addObject:book];
}
}
Applied NSPredicate
NSPredicate *predicate =
[NSPredicate predicateWithFormat:#"publisher == %#", #"Apress" ];
NSArray *filtered = [bookshelf filteredArrayUsingPredicate:predicate];
I think you have forgot the type casting of the array to the class name.
Try to do like this
cell.textLabel.text=((ClassName *)[arrOfObjects objectAtIndex:indexPath.row]).Title;
and for predicate i will suggest you to go through this example

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];

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];