NSMutableArray and NSPredicate filtering

4 Solutions Collect From Internet About “NSMutableArray and NSPredicate filtering”

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

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

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

NSPredicate *pNewsCard = [NSPredicate predicateWithFormat:@"feedType = %@", @"NewsCard"];

NSArray *filteredNewsCard = [arrayTotalFeed filteredArrayUsingPredicate:pNewsCard];

feedType is the property of a Custom object to be compared and arrayTotalFeed is the array of Custom objects.