kvc簡述
kvc即鍵值編碼,在iOS中的應用主要體現在開發者通過key訪問對象的屬性或給對象的屬性賦值。這樣做最主要的好處是把訪問和改變屬性的動作放在了運行時,不需要再編譯時確定
kvc常用的四個方法
(nullable id)valueForKey:(NSString *)key;? ? ? ? ? ? ? ? ? ? ? ? ? //直接通過Key來取值
- (void)setValue:(nullable id)value forKey:(NSString *)key;? ? ? ? ? //通過Key來設值
- (nullable id)valueForKeyPath:(NSString *)keyPath;? ? ? ? ? ? ? ? ? //通過KeyPath來取值
- (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath;? //通過KeyPath來設值
forKeyPath包含了forKey的功能,以后使用forKeyPath就可以了
forKeyPath中可以利用.運算符, 就可以一層一層往下查找對象的屬性。而forKey是無法識別.運算符的。
kvc的具體實現原理
setValue:forKey:賦值原理如下:
去模型中查找有沒有對應的setter方法:例如:setIcon方法,有就直接調用這個setter方法給模型這個屬性賦值[self setIcon:dic[@"icon"]];
如果找不到setter方法,接著就會去尋找有沒有icon屬性,如果有,就直接訪問模型中的icon屬性,進行賦值,icon=dict[@"icon"];
如果找不到icon屬性,接著又會去尋找_icon屬性,如果有,直接進行賦值_icon=dict[@"icon"];如果都找不到就會報錯:[setValue:forUndefinedKey:]
如果對某個類,不允許使用KVC,可以通過設置 accessInstanceVariablesDirectly 控制
KVC內部的實現
比如說如下的一行KVC的代碼:
[site setValue:@"sitename" forKey:@"name"];
就會被編譯器處理成:
SEL sel = sel_get_uid ("setValue:forKey:");
IMP method = objc_msg_lookup (site->isa,sel);
method(site, sel, @"sitename", @"name");
這下KVC內部的實現就很清楚的清楚了:一個對象在調用setValue的時候,(1)首先根據方法名找到運行方法的時候所需要的環境參數。(2)他會從自己isa指針結合環境參數,找到具體的方法實現的接口。(3)再直接查找得來的具體的方法實現。
kvo簡述
KVO其實是一種觀察者模式,利用它可以很容易實現視圖組件和數據模型的分離,當數據模型的屬性值改變之后作為監聽器的視圖組件就會被激發,激發時就會回調監聽器自身。在ObjC中要實現KVO則必須實現NSKeyValueObServing協議,不過幸運的是NSObject已經實現了該協議,因此幾乎所有的ObjC對象都可以使用KVO
在ObjC中使用KVO操作常用的方法如下:
注冊指定Key路徑的監聽器:addObserver: forKeyPath: options:? context:
刪除指定Key路徑的監聽器:removeObserver: forKeyPath、removeObserver: forKeyPath: context:
回調監聽:observeValueForKeyPath: ofObject: change: context:
KVO的使用步驟也比較簡單:
通過addObserver: forKeyPath: options: context:為被監聽對象(它通常是數據模型)注冊監聽器
重寫監聽器的observeValueForKeyPath: ofObject: change: context:方法
由于我們還沒有介紹過IOS的界面編程,這里我們還是在上面的例子基礎上繼續擴展,假設當我們的賬戶余額balance變動之后我們希望用戶可以及時獲得通知。那么此時Account就作為我們的被監聽對象,需要Person為它注冊監聽(使用addObserver:
forKeyPath: options:
context:);而人員Person作為監聽器需要重寫它的observeValueForKeyPath: ofObject: change:
context:方法,當監聽的余額發生改變后會回調監聽器Person監聽方法(observeValueForKeyPath: ofObject:
change: context:)。
。下面通過代碼模擬上面的過程:
Account.h
/
//? Account.h
//? KVCAndKVO
//
//? Created by Kenshin Cui on 14-2-16.
//? Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//#import@interfaceAccount : NSObject#pragmamark - 屬性#pragmamark 余額
@property(nonatomic,assign)floatbalance;
@end
Account.m
//
//? Account.m
//? KVCAndKVO
//
//? Created by Kenshin Cui on 14-2-16.
//? Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//#import"Account.h"@implementation Account
@end
Person.h
/
//? Person.h
//? KVCAndKVO
//
//? Created by Kenshin Cui on 14-2-16.
//? Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//#import@classAccount;
@interfacePerson : NSObject{
@private
int_age;
}#pragmamark - 屬性#pragmamark 姓名
@property(nonatomic,copy) NSString *name;#pragmamark 賬戶
@property(nonatomic,retain) Account *account;#pragmamark - 公共方法#pragmamark 顯示人員信息
-(void)showMessage;
@end
Person.m
//
//? Person.m
//? KVCAndKVO
//
//? Created by Kenshin Cui on 14-2-16.
//? Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//#import"Person.h"#import"Account.h"@implementation Person#pragmamark - 公共方法#pragmamark 顯示人員信息
-(void)showMessage{
NSLog(@"name=%@,age=%d",_name,_age);
}#pragmamark 設置人員賬戶
-(void)setAccount:(Account *)account{
_account=account;//添加對Account的監聽[self.account addObserver:self forKeyPath:@"balance"options:NSKeyValueObservingOptionNew context:nil];
}#pragmamark - 覆蓋方法#pragmamark 重寫observeValueForKeyPath方法,當賬戶余額變化后此處獲得通知
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void*)context{if([keyPath isEqualToString:@"balance"]){//這里只處理balance屬性NSLog(@"keyPath=%@,object=%@,newValue=%.2f,context=%@",keyPath,object,[[change objectForKey:@"new"] floatValue],context);
}
}#pragmamark 重寫銷毀方法
-(void)dealloc{
[self.account removeObserver:self forKeyPath:@"balance"];//移除監聽
//[super dealloc];//注意啟用了ARC,此處不需要調用}
@end
main.m
//
//? main.m
//? KVCAndKVO
//
//? Created by Kenshin Cui on 14-2-16.
//? Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//#import#import"Person.h"#import"Account.h"intmain(intargc,const char* argv[]) {
@autoreleasepool {
Person *person1=[[Person alloc]init];
person1.name=@"Kenshin";
Account *account1=[[Account alloc]init];
account1.balance=100000000.0;
person1.account=account1;
account1.balance=200000000.0;//注意執行到這一步會觸發監聽器回調函數observeValueForKeyPath: ofObject: change: context:
//結果:keyPath=balance,object=,newValue=200000000.00,context=(null)}return0;
}
在上面的代碼中我們在給人員分配賬戶時給賬戶的balance屬性添加了監聽,并且在監聽回調方法中輸出了監聽到的信息,同時在對象銷毀時移除監聽,這就構成了一個典型的KVO應用。