按照预设的要求,查询满足预设条件的对象数组元素,以此组成新的对象数组。
1—— 使用 NSPredicate (断言)类的实例,定义搜索条件;
2——使用原始数组的 filteredArrayUsingPredicate: (使用断言对数组进行筛选)方法,该方法会返回一个新的,由所有满足筛选条件组成的对象数组。
使用了之前的 Goods 类
#import <Foundation/Foundation.h>
#import "Goods.h"
int int main(int argc, char const *argv[])
{
autoreleasepool{
Goods *g1 = [[Goods alloc] initWithName:@"orange juice" price:7];
Goods *g2 = [[Goods alloc] initWithName:@"milk" price:12];
Goods *g3 = [[Goods alloc] initWithName:@"cookies" price:10];
Goods *g4 = [[Goods alloc] initWithName:@"banana" price: 6];
Goods *g5 = [[Goods alloc] initWithName:@"apple" price: 5];
NSArray *listOfGoods = [NSArray arrayWithObjects: g1,g2,g3,g4,g5, nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"price <= 10"];
NSArray *predicatedGoods = [listOfGoods filteredArrayUsingPredicate: predicate];
[listOfGoods makeObjectsPerformSelector:@selector(printResult:)];
}
return 0;
}
结果:
The price of orange juice is 7
The price of cookies is 10
The price of banana is 6
The price of apple is 5