iOS 查询数组中的对象
通常情况下,根据一个条件在数组中查询出匹配的对象的方式有如下几种:
(1)遍历数组,然后将每一个Item和这个条件进行比对,过滤出匹配的对象
显然这个效率比较低
(2)iOS提供另一个效率较高的查询方法,谓词NSPredicate,使用方法如下
C代码 收藏代码
1.NSString 对象
NSArray *array =@["123", @"234" , @"345"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [cd] %@", "2"];
NSArray *filterdArray = [array filterdArrayUsingPredicate:predicate];
NSLog(@"%@", filterdArray );
//output : @"123", "234"
2.含有属性的对象
@interface Person: NSObject
{
NSString *_name;
NSString *_telephone;
NSInteger _id;
}
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *telephone;
@property (nonatomic, assign) NSInteger id;
@end
//
1).等于查询
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", "Ansel"];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
2).模糊查询
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS %@", @"A"]; //predicate只能是对象
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
更详细的用法,请见这个帖子:
http://www.cnblogs.com/thefeelingofsimple/archive/2013/01/31/2886915.html