關於KVC(Key-Value-Coding)鍵-值編碼的概念
1、鍵-值編碼是一種用於間接訪問對象屬性的機制,使用該機制不需要調用setter、getter方法,和變數執行個體就可以訪問對象的屬性。
2、鍵-值編碼方法在OC的非正式協議(類目)NSKeyCodingValue中被聲明,預設的實現方法有NSObject提供。
3、鍵-值編碼支援帶有對象值的屬性,同時也支援純數值的類型和結構。非對象參數和傳回型別會被識別並自動封裝/解鎖。
下面我們來用KVC(Key-Value-Coding)在沒有getter,setter方法的情況下訪問變數的屬性
如下,沒有setter、getter方法以及@property
.h檔案
#import <Foundation/Foundation.h>@interface Dog : NSObject{ NSString *name;}@end
.m檔案
#import "Dog.h"@implementation Dog@end
main檔案
#import <Foundation/Foundation.h>#import "Dog.h"int main(int argc, const char * argv[]){ @autoreleasepool { Dog *dog = [[Dog alloc]init]; [dog setValue:@"娘希匹" forKey:@"name"];//設定索引值對 NSString *name = [dog valueForKey:@"name"];//根據鍵取值 NSLog(@"The dog's name is ....%@...",name); } return 0;}
列印結果:
2、看到上面的內容我們估計有個疑問,我們怎麼訪問屬性中的屬性呢,我們可以通過路徑的方式來訪問,同時我們也來看看純數值的情況
Dog類的.h檔案
#import <Foundation/Foundation.h>@class Tooth;@interface Dog : NSObject{ NSString *name; int age; Tooth *tooth;}@end
Dog類的.m檔案
#import "Dog.h"@implementation Dog@end
Tooth類的.h檔案
#import <Foundation/Foundation.h>@interface Tooth : NSObject{ int num; NSString *color;}@end
Tooth.m
#import "Tooth.h"@implementation Tooth@end
main檔案
#import <Foundation/Foundation.h>#import "Dog.h"#import "Tooth.h"int main(int argc, const char * argv[]){ @autoreleasepool { Dog *dog = [[Dog alloc]init]; [dog setValue:@"娘希匹" forKeyPath:@"name"]; [dog setValue:@5 forKeyPath:@"age"]; NSString *name = [dog valueForKey:@"name"]; NSNumber *age = [dog valueForKey:@"age"]; NSLog(@"The dog's name is ....%@...",name); NSLog(@"%@",age); Tooth *tooth = [[Tooth alloc]init]; [tooth setValue:@10 forKey:@"num"]; [tooth setValue:@"black" forKey:@"color"]; [dog setValue:tooth forKey:@"tooth"]; NSNumber *toothNum = [dog valueForKeyPath:@"tooth.num"]; NSString *toothColor = [dog valueForKeyPath:@"tooth.color"]; NSLog(@"The dog's teeth num is %@,color is %@",toothNum,toothColor); //下面我們使用路徑的方式 [dog setValue:@12 forKeyPath:@"tooth.num"]; [dog setValue:@"white" forKeyPath:@"tooth.color"]; NSNumber *toothNum1 = [dog valueForKeyPath:@"tooth.num"]; NSString *toothColor1 = [dog valueForKeyPath:@"tooth.color"]; NSLog(@"The dog's teeth num is %@,color is %@",toothNum1,toothColor1); [tooth release]; [dog release]; } return 0;}
列印結果:
二、KVO(Key Value Observing)索引值觀察
索引值觀察是一種使對象擷取其他對象的特定屬性變化的通知機制。
KVO主要用於視圖互動方面,比如介面的某些資料變化了,介面的顯示也跟著需要變化,那就要建立資料和介面的關聯