Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableArray and NSPredicate filtering

I am trying to filter my array with two entities within an object like I have a Person object in which I have name, address, number, email, etc. I am trying to filter my array list of objects with just name and number. How can this be achieved with using NSPredicate?

like image 463
topgun Avatar asked Dec 08 '11 19:12

topgun


3 Answers

Create the predicate (the following assumes that your Person class has name and number string properties):

NSString *nameFilter = @"Steve*";
NSString *numberFilter = @"555-*";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name like %@) or (number like %@)", nameFilter, numberFilter];

Then, filter the array (this assumes you have an NSArray of Person objects):

NSArray *personArray = /* obtain from somewhere */;
NSArray *filtered = [personArray filteredArrayUsingPredicate:pred];

The result will be an array that contains Person objects whose name could be “Steve”, “Steven” etc, and whose number starts with 555-.

Edit

What you're saying doesn't really make sense. You can't remove properties from a class (or rather, you shouldn't). If you just want an array that contains only the names and numbers you'll have to iterate through the array of Person objects:

NSMutableArray *result = [NSMutableArray array];

for (Person *p in personArray)
    [result addObject:[NSString stringWithFormat:"%@ : %@", [p name], [p number]]];
like image 177
dreamlax Avatar answered Nov 03 '22 23:11

dreamlax


i believe you are looking for:

NSPredicate * predicate = [NSPredicate predicateWithFormat:@"name==%@",name];

or if you want similarities for string names you could also use:

NSPredicate * predicate = [NSPredicate predicateWithFormat:@"name like %@",name];

and assuming phone number is just an int, you could use ==, <, <=, etc for number comparisons

then apply it with:

NSArray * filteredarray  = [array filteredArrayUsingPredicate:predicate];
like image 39
user1084563 Avatar answered Nov 03 '22 21:11

user1084563


I prefer using CONTAINS word to do filtering. It's easy to do this job. Or you can combine them together:

NSPredicate * predicate =
 [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@ OR name LIKE[cd] %@", filterName, filterName];

You can refer to OFFICIAL DOC:

BEGINSWITH: The left-hand expression begins with the right-hand expression.

CONTAINS: The left-hand expression contains the right-hand expression.

ENDSWITH: The left-hand expression ends with the right-hand expression.

LIKE: The left hand expression equals the right-hand expression: ? and * are allowed as wildcard characters, where ? matches 1 character and * matches 0 or more characters.

MATCHES: The left hand expression equals the right hand expression using a regex-style comparison according to ICU v3 (for more details see the ICU User Guide for Regular Expressions).

like image 1
Kjuly Avatar answered Nov 03 '22 22:11

Kjuly