Search code examples
iosobjective-cnsmutablearraynsarraynspredicate

How to filter an NSArray using a NSPredicate


I am trying to filter an array of NSDictionaries that I have.

This is what my filter currently looks like:

NSDictionary *selectedItemDictionary = [sortedItemsArray objectAtIndex:indexPath.row];

NSMutableArray *sortedItemsMutableArrayCopy = [sortedItemsArray copy];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"dpc like %@", [selectedItemDictionary objectForKey:@"dpc"]];
[sortedItemsMutableArrayCopy filterUsingPredicate:predicate];

This is what my selectedItemDictionary looks like:

dc = 3;
Cmp = F;
Qty = 0;
dp = 0;

Effectively I am trying to search through sortedItemsArray and make a new array of anything that has the same dc number as the selected row in my UITableViewCell. However with the code above I am receiving this error:

 -[__NSArrayI filterUsingPredicate:]: unrecognized selector sent to instance

Solution

  • filterUsingPredicate: is a method for NSMutable array you are looking for filteredArrayUsingPredicate:

    you can tell from the console output __NSArrayI that you have an immutable array instance.

    if you want a mutable array you need to change [sortedItemsArray copy] to [sortedItemsArray mutableCopy]