//// Person.h// 谓词//// Created by on 14-11-15.// Copyright (c) 2014年 Apple. All rights reserved.//#import@interface Person : NSObject@property(nonatomic, copy) NSString *name;@property(nonatomic) int age;@property(nonatomic, copy) NSString *email;@end
//// Person.m// 谓词//// Created by on 14-11-15.// Copyright (c) 2014年 Apple. All rights reserved.//#import "Person.h"@implementation Person- (NSString *)description{ return [NSString stringWithFormat:@"name=%@, age=%d, email=%@", _name, _age, _email];}@end
//// main.m// 谓词//// Created by on 14-11-15.// Copyright (c) 2014年 Apple. All rights reserved.//#import#import "Person.h"// cocoa中提供了NSPredicate类,指定过滤器的条件。将符合条件的对象保留下来int main(int argc, const char * argv[]) { @autoreleasepool { NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age <= 28"]; // 下面三个是不同过滤条件的方法// NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"age <= %d", 22];// NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"age <= 100 && age >= 50"];// 记住,字符串一定要加''// NSPredicate *predicate3 = [NSPredicate predicateWithFormat:@"name in {'jack', 'tom'}"]; NSMutableArray *mutableArray = [[NSMutableArray alloc] init]; for (int i = 0; i < 10; i++) { Person *person = [[Person alloc] init]; [person setName:@"JACK"]; [person setAge:20 + i]; [person setEmail:@"aa@aa.com"]; [mutableArray addObject:person]; } for (Person *p in mutableArray) { if ([predicate evaluateWithObject:p]) { NSLog(@"age = %d", p.age); } } // 这种方式过滤后返回一个数组 NSArray *predicateArray = [mutableArray filteredArrayUsingPredicate:predicate]; NSLog(@"%@", predicateArray); } return 0;}