KVC(Key-Value Coding,鍵值編碼)與 KVO(Key-Value Observing,鍵值觀察)是 Cocoa 運行時兩項基礎能力。KVC 讓你能用字串鍵名讀寫屬性,KVO 則建立在 KVC 之上,可以監聽某個屬性值的變化並即時收到回調——這是 iOS 早期實現數據驅動界面的主要手段。
下面用一個「股價看板」的小例子把兩者串起來:模型有一個股價屬性,界面上有一個 Label 顯示價格,一個 Button 負責改價。按下按鈕後,Label 無需手動重新賦值,KVO 會自動幫我們更新。
#import "ViewController.h"
#import <Foundation/Foundation.h>
@interface DataModel : NSObject
@property (nonatomic, copy) NSString *stockName;
@property (nonatomic, assign) float price;
@end
@implementation DataModel
@end
@interface ViewController ()
@property UILabel *myLabel;
@property UIButton *myButton;
@property DataModel *model;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.model = [[DataModel alloc] init];
// KVC:以鍵名寫入屬性值
[self.model setValue:@"searph" forKey:@"stockName"];
[self.model setValue:@"10.0" forKey:@"price"];
// 註冊觀察 price,同時取得新值與舊值
[self.model addObserver:self
forKeyPath:@"price"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:nil];
self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(130, 100, 100, 100)];
self.myLabel.layer.masksToBounds = YES;
self.myLabel.layer.cornerRadius = 50;
self.myLabel.textAlignment = NSTextAlignmentCenter;
self.myLabel.textColor = [UIColor cyanColor];
self.myLabel.backgroundColor = [UIColor grayColor];
self.myLabel.text = [NSString stringWithFormat:@"%@",
[self.model valueForKey:@"price"]];
[self.view addSubview:self.myLabel];
self.myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.myButton.frame = CGRectMake(130, 200, 100, 30);
[self.myButton setTitle:@"按鈕" forState:UIControlStateNormal];
[self.myButton addTarget:self
action:@selector(changeValue)
forControlEvents:UIControlEventTouchUpInside];
[self.myButton setBackgroundColor:[UIColor lightGrayColor]];
[self.view addSubview:self.myButton];
}
// 改價:只需賦值,界面更新交給 KVO
- (void)changeValue {
[self.model setValue:@"20.0" forKey:@"price"];
}
#pragma mark - KVO 回調
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if ([keyPath isEqualToString:@"price"]) {
self.myLabel.text = [NSString stringWithFormat:@"%@",
[self.model valueForKey:@"price"]];
}
}
// 一定要移除觀察者,否則會崩潰
- (void)dealloc {
[self.model removeObserver:self forKeyPath:@"price"];
}
@end
一定要成對移除。 dealloc 中的 removeObserver:forKeyPath: 不能省,否則對象釋放後仍收到回調會直接崩潰。
回調線程取決於觸發線程。 如果在子線程改動屬性,observeValueForKeyPath: 也會在子線程觸發;涉及 UI 更新時記得切回主線程。
集合類型需要特殊處理。 直接觀察 NSArray 屬性不會得到內容變化的通知,得改用 mutableArrayValueForKey: 這類 KVC 代理集合,或改用通知。
在後續的 iOS 版本中,KVO 逐步被 NotificationCenter、Target-Action、Delegate 乃至 Combine 取代,但理解它的運作方式,對看懂 NSNotificationCenter、Auto Layout 動畫乃至 Interface Builder 的綁定機制都很有幫助。