键(Key)是?一个字符串?用来标识对象?里?面的?一个指定的属性。?一般?一个键对应对象的存取?方法或 实例变量。键必须是ASCII码,?一般以?小写字?母开始,不能包含空格。
A key path is a string of dot separated keys that is used to specify a sequence of object properties to traverse. The property of the first key in the sequence is relative to the receiver, and each subsequent key is evaluated relative to the value of the previous property.
键路径(Key Path)是?一个由点进?行分割的?一系列键组成的字符串
键路径的概念和表示:可以在对象和不同的变量名称之间用圆点分开来表示.
注意:
键路径的深度是任意的,具体取决于对象之间的关系的复杂度
- (void)setValue:(id)value forKey:(NSString *)key
- (id)valueForKey:(NSString *)key
- (id)valueForKey:(NSString *)key //以 key 作为标示符,获取其对应的属性值
- (void)setValue:(id)value forKey:(NSString *)key //以 key 作为标示符设置其对应的属性值
- (id)valueForUndefinedKey:(NSString *)key
- (void)setNilValueForKey:(NSString *)key
@avg
NSnumber *transactionAverage = [transactions valueForKeyPath:@"@avg.amount"];
@count
NSNumber *numberOfTransactions = [transactions valueForKeyPath:@"@count"]
?;
@max
NSDate *latestDate = [transactions valueForKeyPath:@"@max.date"];
@min
NSDate *earliestDate = [transactions valueForKeyPath:@"@min.date"];
@sum
NSNumber *amountSum = [transactions valueForKeyPath:@"@sum.amount"];
使用键值和键路径的方法比较简单,我就直接用一个 KVC在集合中的使用来演示
创建一个 QYPerson 类继承于 NSObject
#import <Foundation/Foundation.h>
@class QYCourse;
@interface QYPerson : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) QYCourse *course;
@property (nonatomic, assign) NSInteger point;
@property (nonatomic, strong) NSArray *persons;
@end
在 main.m 函数中
int main(int argc, const char * argv[]) {
@autoreleasepool {
QYPerson *person = [[QYPerson alloc] init];
QYPerson *p1 = [[QYPerson alloc] init];
QYPerson *p2 = [[QYPerson alloc] init];
QYPerson *p3 = [[QYPerson alloc] init];
[p1 setValue:@"78" forKey:@"point"];
[p2 setValue:@"87" forKey:@"point"];
[p3 setValue:@"98" forKey:@"point"];
NSArray *array = @[p1,p2,p3];
[person setValue:array forKey:@"persons"];
NSLog(@"other persons‘ achievement info:%@",[person valueForKeyPath:@"persons.point"]);
NSLog(@"all persons‘ number is %@",[person valueForKeyPath:@"persons.@count"]);
NSLog(@"the max achievement :%@",[person valueForKeyPath:@"persons.@max.point"]);
NSLog(@"the min achievement :%@",[person valueForKeyPath:@"persons.@min.point"]);
NSLog(@"the avg achievement :%@",[person valueForKeyPath:@"persons.@avg.point"]);
}
return 0;
}
输出的结果如下:
2015-07-29 15:25:48.856 KVCDemo[2968:1026943] other persons‘ achievement info:(
78,
87,
98
)
2015-07-29 15:25:48.856 KVCDemo[2968:1026943] all persons‘ number is 3
2015-07-29 15:25:48.856 KVCDemo[2968:1026943] the max achievement :98
2015-07-29 15:25:48.856 KVCDemo[2968:1026943] the min achievement :78
2015-07-29 15:25:48.876 KVCDemo[2968:1026943] the avg achievement :87.666666666666666666666666666666666666
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/www_nyp_boke/article/details/47154617