Filtering objects from array by a property, using the method filteredArrayUsingPredicate

15,784

Try this:

NSString *propertyName = @"type";
NSArray *eventsArray = [[[self currentPerson] events] allObjects];
NSPredicate *predicte = [NSPredicate predicateWithFormat:
                         @"%k like %@",propertyName, filteredWord];
NSArray *filteredArray = [eventsArray filteredArrayUsingPredicate:predicte];

You ignore the filtered result. The filteredArrayUsingPredicate: returns a new instance of NSArray. It doesn't filter the original array in place, because NSArray objects are immutable. You either have to make an NSMutableArray and then use filterUsingPredicate: to filter the array in place, or you have to do something with the returned array of filteredArrayUsingPredicate: (log it, save it etc...)

Don't use single quotes around the property. (thanks for the clue @MartinR)

Share:
15,784
Dennis
Author by

Dennis

Updated on June 04, 2022

Comments

  • Dennis
    Dennis almost 2 years

    I can't understand how to use predicate, I have a very long code to filter objects from array by property "type" and suddenly I saw method "filteredArrayUsingPredicate" that can make my life better. I try write predicates but I always get errors; can someone show me how to write it right?

    I have method - (void) filterData: (NSString *)filteredWord:

    I also have array with objects (Event): NSArray *eventsArray. I want use a filteredArrayUsingPredicate to get new array with objects (Event) where their property (type) is equal filterWord. Note that Event is Core Data Managed subclass.

    Is it even possible to do this with predicate?

    One of my attempts:

    NSString *propertyName = @"type";
    NSArray *eventsArray = [[[[self currentPerson] events] objectEnumerator]allObjects];
    NSPredicate *predicte = [NSPredicate predicateWithFormat:@"%k like '%@'",propertyName,filteredWord];
    [eventsArray filteredArrayUsingPredicate:predicte];