一次,被问到kvc有什么作用,蓬头垢面的我只答到,获取私有变量。。。
百度一下才发现,kvc竟然有这么多 帅气 的骚操作,开始萌动了写一篇文章的想法
感兴趣的同学可以搜一下iOS官方文档 (关键词:Aggregation Operators)
首先,创建一个类如下
@interfaceTransaction:NSObject
@property(nonatomic)NSString*payee;// To whom
@property(nonatomic)NSNumber*amount;// How much
@property(nonatomic)NSDate*date;// When
@end
Transaction类的测试数据如下
Transaction类数据聚合操作 Aggregation Operators
@avg 返回集合中amount的平均值(遇到nil会用0替代)
NSNumber *transactionAverage = [self.transactions valueForKeyPath:@"@avg.amount"]; //456.54
@count 返回集合数量
NSNumber *numberOfTransactions = [self.transactions valueForKeyPath:@"@count"]; //13
@max 返回最大值(使用了compare:方法,所以比较的属性要能响应此方法)
NSDate *latestDate = [self.transactions valueForKeyPath:@"@max.date"]; //Jul 15, 2016
@min 返回最小值(类似@max)
NSDate *earliestDate = [self.transactions valueForKeyPath:@"@min.date"]; //Dec 1, 2015
@sum 返回属性的总和
NSNumber *amountSum = [self.transactions valueForKeyPath:@"@sum.amount"];//5935.00
数组操作 Array Operators
@distinctUnionOfObjects 返回根据指定的属性去重的数组
NSArray *distinctPayees = [self.transactions valueForKeyPath:@"@distinctUnionOfObjects.payee"];
//Car Loan, General Cable, Animal Hospital, Green Power, Mortgage.
@unionOfObjects 返回根据指定的属性生成的数组(不会去重)
NSArray *payees = [self.transactions valueForKeyPath:@"@unionOfObjects.payee"];
//Green Power, Green Power, Green Power, Car Loan, Car Loan, Car Loan, General Cable, General Cable, General Cable, Mortgage, Mortgage, Mortgage, Animal Hospital.
@distinctUnionOfArrays 返回根据指定的属性去重的所有嵌套数组的属性集合
现在再创建一个数组 moreTransactions,跟之前的transactions类似。数据如下
moreTransactionsNSArray *arrayOfArrays = @[self.transactions, self.moreTransactions];
NSArray *collectedDistinctPayees = [arrayOfArrays valueForKeyPath:@"distinctUnionOfArrays.payee"];
//Hobby Shop, Mortgage, Animal Hospital, Second Mortgage, Car Loan, General Cable - Cottage, General Cable, Green Power.
@unionOfArrays 返回所有嵌套数组中指定属性的数组
NSArray *collectedPayees = [arrayOfArrays valueForKeyPath:@"@unionOfArrays.payee"];
//Green Power, Green Power, Green Power, Car Loan, Car Loan, Car Loan, General Cable, General Cable, General Cable, Mortgage, Mortgage, Mortgage, Animal Hospital, General Cable - Cottage, General Cable - Cottage, General Cable - Cottage, Second Mortgage, Second Mortgage, Second Mortgage, Hobby Shop.
@distinctUnionOfSets 返回所有嵌套set中指定属性的set
此操作与distinctUnionOfArrays极为类似,只是请求对象要是NSSet,并且返回值也是NSSet。
实例方法调用 返回包括了每个元素调用了实例方法后的数组
NSArray *lowers = @[@"huafei",@"fenghua",@"Xiaoming",@"Th"];
NSArray *uppers = [lowers valueForKeyPath:@"uppercaseString"];
注意:
1、distinctUnionOfObjects返回的数组跟之前数组顺序相同吗?
答:跟之前数组顺序不一致,乱序。。。
2、distinctUnionOfArrays,若self.transactions与self.moreTransactions里面的payee有相同的,那么会返回什么结果?
答:[arrayOfArrays valueForKeyPath:@"@distinctUnionOfArrays.payee"]返回的数组总是去重的。
3、可以自己定义key吗?
答:会崩溃,但有人通过iOS的方法交换,自己重写valueForKeyPath,然后自己解析key来实现一些功能。。。
网友评论