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];
Try this:
You ignore the filtered result. The
filteredArrayUsingPredicate:returns a new instance of
NSArray. It doesn’t filter the originalarray in place, because
NSArrayobjects are immutable. You eitherhave to make an
NSMutableArrayand then use
filterUsingPredicate:to filter the array in place, oryou 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)