想项目有可能会遇到按照一定条件对某一个数组进行筛选。 直接遍历数组,取符合条件的对象放到一个新数组效率可能不高。
下面介绍一个更简便的方法来实现
NSPredicate类主要用来指定过滤器的条件,该对象可以准确的描述所需条件,对每个对象通过谓词进行筛选,判断是否与条件相匹配。谓词是指在计算机中表示计算真假值的函数。原理和用法都类似于SQL查询中的where,作用相当于数据库的过滤取。主要用于从集合中分拣出符合条件的对象或者数据模型,也可以用于字符串的正则匹配. 一般的, NSPredicate的筛选过滤的条件可以是, 逻辑运算符号(> , < , =),范围运算符(IN,BETWEEN),字符的包含/匹配/模糊搜索(BEGINSWITH,ENDSWITH,CONTAINS,LIKE), 正则表达式(MATCHES)等.
NSPredicate用法 1.创建NSPredicate NSPredicate *predicate = [NSPredicate predicateWithFormat:@"过滤条件"]; 2.判断指定的对象是否满足NSPredicate创建的过滤条件 [predicate evaluateWithObject:model]; 3.将array通过创建的predicate进行过滤,并返回符合条件的数据 NSArray *resultArr = [array filteredArrayUsingPredicate:predicate];
具体实现,首先我们定义一个Peron类
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) NSInteger age;
- (instancetype)initWithName:(NSString *)name age:(NSInteger)age;
-(void)printPerson ;
#import "Person.h"
@interface Person()
@end
@implementation Person
- (instancetype)initWithName:(NSString *)name age:(NSInteger)age {
self = [super init];
if (self) {
self.name = name;
self.age = age;
}
return self;
}
-(void)printPerson {
NSLog(@"Name is %@ ageis %zd ",_name, _age);
}
在定义个NSMutableArray的Category NSMutableArray+Extended
#import <Foundation/Foundation.h>
@interface NSMutableArray (Extended)
/**
数组筛选属性为Int类型的对象
@param condition 筛选条件
@param value 属性对应的值
@return 筛选后的数组
*/
-(NSMutableArray*)getArrayWithInt:(NSString*)condition value:(NSInteger)value;
/**
数组筛选属性为NSString类型的对象
@param key 对象对应的属性字段
@param value 对象对应的值
@return 筛选后的数组
*/
-(NSMutableArray*)getArrayWithString:(NSString*)key value:(NSString*)value;
@end
#import "NSMutableArray+Extended.h"
@implementation NSMutableArray (Extended)
-(NSMutableArray*)getArrayWithInt:(NSString*)condition value:(NSInteger)value
{
NSPredicate *inputPredicate=[NSPredicate predicateWithFormat:condition,value];
NSMutableArray *newMutableArray = [NSMutableArray arrayWithArray:[self filteredArrayUsingPredicate:inputPredicate]];
return newMutableArray;
}
-(NSMutableArray*)getArrayWithString:(NSString*)key value:(NSString*)value
{
NSPredicate *inputPredicate=[NSPredicate predicateWithFormat:@"%K like[cd] %@",key, [NSString stringWithFormat:@"*%@*",value]];
NSMutableArray *newMutableArray = [NSMutableArray arrayWithArray:[self filteredArrayUsingPredicate:inputPredicate]];
return newMutableArray;
}
@end
下面调用
Person *p1 = [[Person alloc]initWithName:@"aa" age:18];
Person *p2 = [[Person alloc]initWithName:@"bb" age:18];
Person *p3 = [[Person alloc]initWithName:@"cc" age:18];
Person *p4 = [[Person alloc]initWithName:@"dd" age:22];
Person *p5 = [[Person alloc]initWithName:@"ee" age:15];
NSMutableArray *personArr = [NSMutableArray arrayWithObjects:p1,p2,p3,p4,p5, nil];
// 取出数组中age = 18的对象
[[personArr getArrayWithInt:@"age=%d" value:18] makeObjectsPerformSelector:@selector(printPerson)];
// 取出数组中name = @"aa"的对象
[[personArr getArrayWithString:@"name" value:@"aa"] makeObjectsPerformSelector:@selector(printPerson)];