NSPredicate查询数组(Objective-C 开发范例)

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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值