您只需将其写入您的谓词中,例如,假设您有一个带有调用方法的对象,isOdd
并且您希望过滤数组以仅包含返回 true for 的对象isOdd
,您可以这样做:
#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);
}
}
当然,这也适用于其他方式,您的谓词也可以读取isOdd == false
,或者您可以添加更多要求以使对象通过。例如isOdd == true AND foo == bar
。您可以在文档中阅读有关NSPredicate
语法的更多信息NSPredicate
。