最近研究一下KVO的實現(xiàn)原理瞭稼,寫篇博文記錄下眷昆;
用以下例子做說明:
創(chuàng)建兩個類CYPerson和CYPhone匣距,CYPhone中屬性?electricity酥艳;
?當phone對象的屬性?electricity改變時壹堰,person進行處理操作拭卿,代碼如下
#import <Foundation/Foundation.h>
@interface CYPhone : NSObject
@property(nonatomic,assign)NSInteger electricity;
@end
CYPerson需實現(xiàn):- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
#import "CYPerson.h"
@implementation CYPerson
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
NSLog(@"object:%@,keyPath:%@,change:%@",object,keyPath,change);
}
@end
#import "ViewController.h"
#import "CYPerson.h"
#import "CYPhone.h"
@interface ViewController ()
@property (nonatomic ,strong) UITextField *textF;
@property (nonatomic ,strong) CYPerson *person;
@property (nonatomic ,strong) CYPhone *phone;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor grayColor];
_person = [CYPerson new];
_phone = [CYPhone new];
[_phone addObserver:self.person forKeyPath:@"electricity" options:NSKeyValueObservingOptionNew context:nil];
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(20, 100, [UIScreen mainScreen].bounds.size.width - 40, 40)];
textField.backgroundColor = [UIColor whiteColor];
[self.view addSubview:textField];
_textF = textField;
UIButton *changeBtn = [[UIButton alloc]initWithFrame:CGRectMake(20, 175, [UIScreen mainScreen].bounds.size.width - 40, 40)];
[changeBtn setTitle:@"確認電量" forState:UIControlStateNormal];
[changeBtn addTarget:self action:@selector(changeBtnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:changeBtn];
}
- (void)changeBtnClick
{
self.phone.electricity = [self.textF.text integerValue];
}
輸入數(shù)字,點擊確認后對phone的electricity值進行改變贱纠,我們添加斷點調(diào)試峻厚,控制臺結(jié)果如下
isa,簡單點說其指向的就是真實類型谆焊;
phone對象的類為CYPhone惠桃,isa指向的是NSKVONotifying_CYPhone,說明當我們在使用KVO的時候,runtime過程中會動態(tài)的創(chuàng)建一個類NSKVONotifying_對象類名辖试,進而實現(xiàn)觀察辜王。
?如有問題請大家提出,多多指教罐孝,共同進步呐馆。