How to filter a NSArray - ios

Hey i want to filter an NSArray. In this Array is a lot of information like name, town, telephonenumber, and so on. But some towns are twice or three times in the array.
I have property with a town in it.
So i want only those objects from the arry which match with the property.
For example:
in the Array stands:
Frank, New York, 123456
Oliver, New York, 123456
Thomas, Boston, 123456
and when the property is New York i want olny objects 1 and 2.
Does anyone has an idea how i can do it?
This is my code:
NSString *filterString = newsArticle;
NSPredicate *prediacte = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"Ort == '%#'",filterString]];
newsTownArray = [news filteredArrayUsingPredicate:predicate];
and when i come to the line:
cell.textLabel.text=[[newsTownArray objectAtIndex:indexPath.row] objectForKey:"Name"];

You need to use NSPredicate for this.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"town == 'New York'"];
[yourArray filterUsingPredicate:predicate];
Dynamically you can create predicate like:
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"town == '%#'",yourInput]];
Here yourInput is a NSString which holds the required town name.
Please check these articles for more details:
codeproject
useyourloaf

Use this code
NSMutableArray *subpredicates = [NSMutableArray array];
for(NSString *term in arryOfWordsToBeSearched) {
NSPredicate *p = [NSPredicate predicateWithFormat:#"self contains[cd] %#",term];
[subpredicates addObject:p];
}
NSPredicate *filter = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
result = (NSMutableArray*)[arryOfDummyData filteredArrayUsingPredicate: filter];

However you can do it within an array with the use of NSPredicate, but I will suggest to do bit differently, this will add up to your code and good programming way.
Create a custom class Person having these properties name, city and telephone.
Create an array that will store objects of Person.
After this you can manipulate/ filter / sort etc quite easily.
NSString *filterCity=#"Delhi";
NSMutableArray *yourArray=[NSMutableArray arrayWithArray:self.persons];
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"city == '%#'",filterCity]];
[yourArray filterUsingPredicate:predicate];
NSLog(#"Filtered");
for (Person *per in yourArray) {
NSLog(#"Name: %#, City: %#, Telephone: %#",per.name, per.city, per.telephone);
}

Related

NSPredicate how to filter object fields

How do I filter an array of objects by a specific field?
My code:
NSMutableArray *inputArray = [[NSMutableArray alloc]init];
Person *person = [[Person alloc]init];
person.first_name = #"John";
[inputArray addObject: person];
person = [[Person alloc]init];
person.first_name = #"Jack";
[inputArray addObject: person];
NSString *expression = [NSString stringWithFormat:#"SUBQUERY(inputArray, $object, $object.first_name CONTAINS[c] J"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:expression];
NSMutableArray *filteredArray = [[inputArray filteredArrayUsingPredicate:predicate]mutableCopy];
NSLog(#"Count should be 2: %lu",(unsigned long)filteredArray.count);
This is the error I get:
'NSInvalidArgumentException', reason: 'Unable to parse the format string "SUBQUERY(inputArray, $object, $object.first_name CONTAINS[c] J"'
This is a basic example for testing. The real-case scenario is that I have an array of objects (Person or whatever) and I want to filter that array by certain fields within the objects ie first_name. As the user types we will filter a visual list based on what they type - so typing "J" would yield 2 results, but then when they type "Jo" only "John" appears on the list.
What am I doing wrong?
EDIT
Still doesn't seem to be working. Updated code:
DOVisitor *vi = [inputArray objectAtIndex:0];
NSLog(#"NAME: %#",vi.first_name);
NSPredicate *firstNamePredicate=[NSPredicate predicateWithFormat:#"first_name LIKE[cd] %#", #"Jo"];
NSPredicate *lastNamePredicate =[NSPredicate predicateWithFormat:#"last_name LIKE[cd] %#", #"Jo"];
NSPredicate *finalPredicate = [NSCompoundPredicate orPredicateWithSubpredicates : #[firstNamePredicate, lastNamePredicate]];
NSArray *filteredArray = [[inputArray filteredArrayUsingPredicate:finalPredicate]mutableCopy];
NSLog(#"Count should be 1: %d", [filteredArray count]);
I get an empty array back. However when I print the first object of the inputArray the console logs "John"
EDIT
Using CONTAINS instead of LIKE does the trick
You don't need a subquery for this, this is a very basic filter.
NSPredicate * predicate = [NSPredicate predicateWithFormat:#"first_name CONTAINS[cd] %#", #"j"];
Let us say you have Person object and you are trying to search for both firstName and lastName, then you can use:
NSPredicate *firstNamePredicate=[NSPredicate predicateWithFormat:#"firstName LIKE[cd] %#", #"Jo"];
NSPredicate *lastNamePredicate =[NSPredicate predicateWithFormat:#"lastName LIKE[cd] %#", #"Jo"];
NSPredicate *finalPredicate = [NSCompoundPredicate orPredicateWithSubpredicates : #[firstNamePredicate, lastNamePredicate]];
The final Predicate is generated by oring the previous predicates. So even if Jo is present in firstName or lastName, that Person object will pass the predicate test.
Edit:
Get filtered objects with above predicate
NSArray *filteredArray = [inputArray filteredArrayUsingPredicate:finalPredicate];

How to filter NSArray using two NSPredcates

I would like to filter an NSArray of NSDictionaries, however I would like to filter the result using one, two or even three NSPredicate values?
Currently I am filtering my array by doing this.
NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"parts == %#", filterString];//keySelected is NSString itself
NSMutableArray *filteredArray = [NSMutableArray arrayWithArray:[currentParts filteredArrayUsingPredicate:predicateString]];
sortedItemsArray = [filteredArray mutableCopy];
But I am not sure how I would do this using two predicates?
The other two predicates individually look like the one above accept different keys.
NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"area == %#", filterString];
and
NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"item == %#", filterString];
What I was thinking is that maybe you could have something like
NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"stage == %# area == %#", filterString, areaflterstring];
But I don't think that's possible.
It is possible, but you need to tell the predicate how to combine the parts, like:
NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"stage == %# AND area == %#", filterString, areaflterstring];
You can alternatively use NSCompoundPredicate to combine a number of predicates.

Core Data and Predicate

Say I have an Entity Department that has a to-many relationship with Persons. I want to be able to search the Department Sports to see if Person Scott Olsen works there. The Person Scott Olsen is not unique (there may be 3 Scotts working in 3 different Departments).
How can I search the Department Sports to find the Person Scott Olsen that works there and not find the other Scotts?
The basic way I can think of is:
for (Person *person in sports.persons) {
if ([person.name isEqualToString:#"Scott Olsen"]) {
// found him!
}
}
Or:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ANY persons.name == 'Scott Olsen'"];
Department *department = [Department MR_findFirstWithPredicate:predicate];
But I'm unsure if the second returns the Scott Olsen that works in Departement Sports. I suppose I could then check
if ([department.name isEqualToString:#"Sports"])
But it seems like there should be a better way to do it with a NSPredicate, but I can't figure it out.
Is this what you are looking for?
NSString *name = #"Scott Olsen";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name = %#", name];
NSSet *filtered = [sports.persons filteredSetUsingPredicate:predicate];
Or (your question changed after I posted the above code):
NSString *name = #"Scott Olsen";
NSString *department = #"Sports";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name = %# AND department = %#",
name, department];
Person *person = [Person MR_findFirstWithPredicate:predicate];
(assuming that you have an inverse relationship "department" from Person to Department).
Just add second expression in your predicate:
[NSPredicate predicateWithFormat:#"name == 'Sports' && ANY persons.name == 'Scott Olsen'"];

NSPredicate and BeginsWith

I would like to figure out the NSPredicate that will search my Core data for words that begins with:
For example:
description field in the core data has text like this:
My name is Mike
My name is Moe
My name is Peter
My name is George
If I search 'My name is' I need to get the 3 lines
If I search 'My name is M' I need to get the first 2 lines
I tried the code below, but can't get what I need. My guess I need a regular expression, but not sure how to do it.
[NSPredicate predicateWithFormat:#"desc beginswith [cd] %#",word];
I did it this way recently and worked fine. Try it out. I see I don't have [cd] and beginswith but contains. You could give it a try.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains %#", textField.text];
NSArray *list = [allWords filteredArrayUsingPredicate:predicate];
for(NSString *word in list){
NSLog(#"%#",word);
}
After reading the comments on the starting post:
First of all, you should split up the words in the string from the textfield:
NSArray *myWords = [textField.text componentsSeparatedByString:#" "];
Then doing the same like you first would:
for(NSString *wordFromTextField in myWords){
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains %#", wordFromTextField];
NSArray *list = [allWords filteredArrayUsingPredicate:predicate];
for(NSString *word in list){
NSLog(#"%#",word);
}
}
Instead of NSLogging the words you could add them to an array of course.

NSPredicate possibly matching multiple properties

I have a Car class with instance variables such as "color" and "make".
I need a NSPredicate that allows me to search for either color or make or both.
NSPredicate*predicate=[NSPredicate predicateWithFormat:#"(color contains[c] %#) AND (make contains[c] %#)", chosenColor,chosenMake];
This predicate requires that there is BOTH a color and a make. If the user only gives a color, no results will be returned because the make then will be "nil". No cars has nil for any instance variables.
Also, the search will be for many variables, not only color and make, so an if/case situation is not wanted. Is there any options that gives my the possibility to search for "AND if NOT nil". I will appreciate any help.
You can build your predicate format dynamically to test only non-nil attributes. More on that here. Also consider making your search diacritic-insensitive (adding a 'd' to your CONTAINS statement). Take "Škoda" for example. You want people to find it with "skoda" as well.
This is pretty easy with the NSCompoundPredicate API:
NSString *chosenColor = ...;
NSString *chosenMake = ...;
NSMutableArray *subpredicates = [NSMutableArray array];
if (chosenColor != nil) {
NSPredicate *p = [NSPredicate predicateWithFormat:#"color contains[cd] %#", chosenColor];
[subpredicates addObject:p];
}
if (chosenMake != nil) {
NSPredicate *p = [NSPredicate predicateWithFormat:#"make contains[cd] %#", chosenMake];
[subpredicates addObject:p];
}
NSPredicate *final = nil;
if ([subpredicates count] > 0) {
final = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
}

Resources