You simply write it into your predicate, for example, lets assume you have an object with a method called isOdd
and you want to filter your array to include only objects that return true for isOdd
, you can do this:
#import <Foundation/Foundation.h>
@interface barfoo : NSObject
{
int number;
}
- (BOOL)isOdd;
- (id)initWithNumber:(int)number;
@end
@implementation barfoo
- (NSString *)description
{
return [NSString stringWithFormat:@"%i", number];
}
- (BOOL)isOdd
{
return (number % 2);
}
- (id)initWithNumber:(int)tnumber
{
if((self = [super init]))
{
number = tnumber;
}
return self;
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
NSMutableArray *array = [NSMutableArray array];
for(int i=0; i<10; i++)
{
barfoo *foo = [[barfoo alloc] initWithNumber:i];
[array addObject:[foo autorelease]];
}
NSLog(@"%@", array); // prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isOdd == true"]; // This is oure predicate. isOdd must be true for objects to pass
NSArray *result = [array filteredArrayUsingPredicate:predicate];
NSLog(@"%@", result);
}
}
Of course this also works the other way around, your predicate could also read isOdd == false
or you can add even more requirements for an object to pass. Eg isOdd == true AND foo == bar
. You can read more about the NSPredicate
syntax in the NSPredicate
documentation.