简体   繁体   中英

Filtering array of objects with predicate by function

I'm pretty new to NSPredicate, and sorry if this is newbie question, but I'v done my research and couldn't find answer to this.

I would like to filter array of custom objects by their function, not property.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ LIKE %@", [times objectAtIndex:x] ,[unit realTime]];
NSArray *filtered  = [objectArray filteredArrayUsingPredicate:predicate];

the objectArray contains only unit Objects. And i would like to filter the array by each object in Array by [unit realTime] method result. Basically I'd like to have filtered array where [times objectAtIndex:x] == [unit realTime] . Is this possible to do?

You can add realTime as an @property() NSDate *realTime; in Unit.h file and then implement realTime method just like how you have already done. That way realTime is a param in class and you are overriding the getter method with your custom implementation. It shouldnt show an undeclared identifier error in this case.

Once you have done that, change the predicate statement as,

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K LIKE %@", unit.realTime, [times objectAtIndex:x]];
NSArray *filtered  = [objectArray filteredArrayUsingPredicate:predicate];

You should use %K to for unit.realTime and not %@ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM