鍵(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
@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:@[email protected]]);
NSLog(@the min achievement :%@,[person valueForKeyPath:@[email protected]]);
NSLog(@the avg achievement :%@,[person valueForKeyPath:@[email protected]]);
}
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