NSPredicate查询数组NSArray
假设你拥有填满了对象的数组,想要根据某些条件(这些条件可以通过iOS 应用表格中的搜索栏等类似控件进行输入)找出数组的某个子集。
解决方案
首先需要的是NSPredicate 对象,NSPredicate 用于定义搜索查询。接下来,可以使用原始数组的filteredArrayUsingPredicate:函数并根据定义的NSPredicate 对象规范返回数组的子集。
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property(strong) NSString *firstName;
@property(strong) NSString *lastName;
@property(assign) int age;
-(id)initWithFirstName:(NSString *)fName lastName:(NSString *)lName
andAge:(int)a;
-(void)reportState;
@end
Person.m
#import "Person.h"
@implementation Person
@synthesize firstName, lastName, age;
-(id)initWithFirstName:(NSString *)fName lastName:(NSString *)lName
andAge:(int)a{
self = [super init];
if (self) {
self.firstName = fName;
self.lastName = lName;
self.age = a;
}
return self;
}
-(void)reportState{
NSLog(@"This person's name is %@ %@ who is %i years old", firstName,
lastName, age);
}
@end
你要定义如下判断,让返回的数组只包含年龄大于30 的Person 对象:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 30"];
判断需要对数组中的对象应用逻辑表达式。这里的age 必须是待查询数组中对象的某个属性。使用的比较运算符与编程时使用的相同。创建好判断后,你只需要使用filteredArrayUsingPredicate:函数并将NSPredicate 对象作为参数传递进去,即可获得数组的子集:
NSArray *arraySubset = [listOfObjects filteredArrayUsingPredicate:predicate];
你会获得另一个数组,该数组只包含与NSPredicate 对象中所定义规范相匹配的那些对象
测试代码
#import <Foundation/Foundation.h>
#import "Person.h"
int main (int argc, const char * argv[])
{
@autoreleasepool {
//Instantiate Person objects and add them all to an array:
Person *p1 = [[Person alloc] initWithFirstName:@"Rebecca"
lastName:@"Smith"
andAge:33];
Person *p2 = [[Person alloc] initWithFirstName:@"Albert"
lastName:@"Case"
andAge:24];
Person *p3 = [[Person alloc] initWithFirstName:@"Anton"
lastName:@"Belfey"
andAge:45];
Person *p4 = [[Person alloc] initWithFirstName:@"Tom"
lastName:@"Gun"
andAge:17];
Person *p5 = [[Person alloc] initWithFirstName:@"Cindy"
lastName:@"Lou"
andAge:6];
Person *p6 = [[Person alloc] initWithFirstName:@"Yanno"
lastName:@"Dirst"
andAge:76];
NSArray *listOfObjects = [NSArray arrayWithObjects:p1, p2, p3, p4,
p5, p6, nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 30"];
NSArray *arraySubset = [listOfObjects
filteredArrayUsingPredicate:predicate];
NSLog(@"PRINT OUT ARRAY SUBSET");
[arraySubset makeObjectsPerformSelector:@selector(reportState)];
}
return 0;
}