本文Demo傳送門:CMKVODemohtml
摘要:這篇文章首先介紹KVO的基本用法,接着探究 KVO (Key-Value Observing) 實現機制,並利用 runtime 模擬實現 KVO的監聽機制:一種Block方式回調,一種Delegate回調。同時,本文也會總結KVO實現過程當中與 runtime 相關的API用法。git
步驟github
❶ 註冊觀察者,實施監聽數組
[self.person addObserver:self
forKeyPath:@"age"
options:NSKeyValueObservingOptionNew
context:nil];
複製代碼
❷ 回調方法,在這裏處理屬性發生的變化bash
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSString *,id> *)change
context:(void *)context {
//...實現監聽處理
}
複製代碼
❸ 移除觀察者app
[self removeObserver:self forKeyPath:@「age"]; 複製代碼
綜合例子框架
//添加觀察者
_person = [[Person alloc] init];
[_person addObserver:self
forKeyPath:@"age"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:nil];
複製代碼
//KVO回調方法
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSString *,id> *)change
context:(void *)context
{
NSLog(@"%@對象的%@屬性改變了,change字典爲:%@",object,keyPath,change);
NSLog(@"屬性新值爲:%@",change[NSKeyValueChangeNewKey]);
NSLog(@"屬性舊值爲:%@",change[NSKeyValueChangeOldKey]);
}
複製代碼
//移除觀察者
- (void)dealloc
{
[self.person removeObserver:self forKeyPath:@"age"];
}
複製代碼
利用了KVO實現鍵值監聽的第三方框架async
KVO 是 Objective-C 對 觀察者模式(Observer Pattern)的實現。當被觀察對象的某個屬性發生更改時,觀察者對象會得到通知。有意思的是,你不須要給被觀察的對象添加任何額外代碼,就能使用 KVO 。這是怎麼作到的?ui
KVO 的實現也依賴於 Objective-C 強大的 Runtime 。Apple 的文檔有簡單提到過 KVO 的實現。Apple 的文檔惟一有用的信息是:被觀察對象的 isa 指針會指向一箇中間類,而不是原來真正的類。Apple 並不但願過多暴露 KVO 的實現細節。
不過,要是你用 runtime 提供的方法去深刻挖掘,全部被掩蓋的細節都會原形畢露。Mike Ash 早在 2009 年就作了這麼個探究,瞭解更多 點這裏。
KVO 的實現:
當你觀察一個對象時,一個新的類會動態被建立。這個類繼承自該對象的本來的類,並重寫了被觀察屬性的 setter
方法。天然,重寫的 setter
方法會負責在調用原 setter
方法以前和以後,通知全部觀察對象值的更改。最後把這個對象的 isa
指針 ( isa 指針告訴 Runtime 系統這個對象的類是什麼 ) 指向這個新建立的子類,對象就神奇的變成了新建立的子類的實例。
這個中間類,繼承自本來的那個類。不只如此,Apple 還重寫了 -class
方法,企圖欺騙咱們這個類沒有變,就是本來那個類。更具體的信息,去跑一下 Mike Ash 的那篇文章裏的代碼就能明白,這裏就再也不重複。
KVO 很強大,沒錯。知道它內部實現,或許能幫助更好地使用它,或在它出錯時更方便調試。但官方實現的 KVO 提供的 API 實在不怎麼樣。
好比,你只能經過重寫 -observeValueForKeyPath:ofObject:change:context:
方法來得到通知。想要提供自定義的 selector ,不行;想要傳一個 block ,門都沒有。並且你還要處理父類的狀況 - 父類一樣監聽同一個對象的同一個屬性。但有時候,你不知道父類是否是對這個消息有興趣。雖然 context 這個參數就是幹這個的,也能夠解決這個問題 - 在 -addObserver:forKeyPath:options:context:
傳進去一個父類不知道的 context。但總以爲框在這個 API 的設計下,代碼寫的很彆扭。至少至少,也應該支持 block 吧。
有很多人都以爲官方 KVO 很差使的。Mike Ash 的 Key-Value Observing Done Right,以及得到很多分享討論的 KVO Considered Harmful 都把 KVO 拿出來吊打了一番。因此在實際開發中 KVO 使用的情景並很少,更多時候仍是用 Delegate 或 NotificationCenter。
注意:如下都是同一個文件:NSObject+Block_KVO.m中寫的
#import "NSObject+Block_KVO.h"
#import <objc/runtime.h>
#import <objc/message.h>
//as prefix string of kvo class
static NSString * const kCMkvoClassPrefix_for_Block = @"CMObserver_";
static NSString * const kCMkvoAssiociateObserver_for_Block = @"CMAssiociateObserver";
複製代碼
- (void)CM_addObserver:(NSObject *)observer forKey:(NSString *)key withBlock:(CM_ObservingHandler)observedHandler
{
//step 1 get setter method, if not, throw exception
SEL setterSelector = NSSelectorFromString(setterForGetter(key));
Method setterMethod = class_getInstanceMethod([self class], setterSelector);
if (!setterMethod) {
@throw [NSException exceptionWithName: NSInvalidArgumentException reason: [NSString stringWithFormat: @"unrecognized selector sent to instance %@", self] userInfo: nil];
return;
}
//本身的類做爲被觀察者類
Class observedClass = object_getClass(self);
NSString * className = NSStringFromClass(observedClass);
//若是被監聽者沒有CMObserver_,那麼判斷是否須要建立新類
if (![className hasPrefix: kCMkvoClassPrefix_for_Block]) {
//【代碼①】
observedClass = [self createKVOClassWithOriginalClassName: className];
//【API註解①】
object_setClass(self, observedClass);
}
//add kvo setter method if its class(or superclass)hasn't implement setter if (![self hasSelector: setterSelector]) { const char * types = method_getTypeEncoding(setterMethod); //【代碼②】 class_addMethod(observedClass, setterSelector, (IMP)KVO_setter, types); } //add this observation info to saved new observer //【代碼③】 CM_ObserverInfo_for_Block * newInfo = [[CM_ObserverInfo_for_Block alloc] initWithObserver: observer forKey: key observeHandler: observedHandler]; //【代碼④】【API註解③】 NSMutableArray * observers = objc_getAssociatedObject(self, (__bridge void *)kCMkvoAssiociateObserver_for_Block); if (!observers) { observers = [NSMutableArray array]; objc_setAssociatedObject(self, (__bridge void *)kCMkvoAssiociateObserver_for_Block, observers, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } [observers addObject: newInfo]; } 複製代碼
kCMkvoClassPrefix_for_Block
的前綴。怎樣新建一個子類?代碼以下所示:- (Class)createKVOClassWithOriginalClassName: (NSString *)className
{
NSString * kvoClassName = [kCMkvoClassPrefix stringByAppendingString: className];
Class observedClass = NSClassFromString(kvoClassName);
if (observedClass) { return observedClass; }
//建立新類,而且添加CMObserver_爲類名新前綴
Class originalClass = object_getClass(self);
//【API註解②】
Class kvoClass = objc_allocateClassPair(originalClass, kvoClassName.UTF8String, 0);
//獲取監聽對象的class方法實現代碼,而後替換新建類的class實現
Method classMethod = class_getInstanceMethod(originalClass, @selector(class));
const char * types = method_getTypeEncoding(classMethod);
class_addMethod(kvoClass, @selector(class), (IMP)kvo_Class, types);
objc_registerClassPair(kvoClass);
return kvoClass;
}
複製代碼
#pragma mark -- Override setter and getter Methods
static void KVO_setter(id self, SEL _cmd, id newValue)
{
NSString * setterName = NSStringFromSelector(_cmd);
NSString * getterName = getterForSetter(setterName);
if (!getterName) {
@throw [NSException exceptionWithName: NSInvalidArgumentException reason: [NSString stringWithFormat: @"unrecognized selector sent to instance %p", self] userInfo: nil];
return;
}
id oldValue = [self valueForKey: getterName];
struct objc_super superClass = {
.receiver = self,
.super_class = class_getSuperclass(object_getClass(self))
};
[self willChangeValueForKey: getterName];
void (*objc_msgSendSuperKVO)(void *, SEL, id) = (void *)objc_msgSendSuper;
objc_msgSendSuperKVO(&superClass, _cmd, newValue);
[self didChangeValueForKey: getterName];
//獲取全部監聽回調對象進行回調
NSMutableArray * observers = objc_getAssociatedObject(self, (__bridge const void *)kCMkvoAssiociateObserver_for_Block);
for (CM_ObserverInfo_for_Block * info in observers) {
if ([info.key isEqualToString: getterName]) {
dispatch_async(dispatch_queue_create(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
info.handler(self, getterName, oldValue, newValue);
});
}
}
}
複製代碼
self.handler = handler;
即負責回調。@interface CM_ObserverInfo_for_Block : NSObject
@property (nonatomic, weak) NSObject * observer;
@property (nonatomic, copy) NSString * key;
@property (nonatomic, copy) CM_ObservingHandler handler;
@end
@implementation CM_ObserverInfo_for_Block
- (instancetype)initWithObserver: (NSObject *)observer forKey: (NSString *)key observeHandler: (CM_ObservingHandler)handler
{
if (self = [super init]) {
_observer = observer;
self.key = key;
self.handler = handler;
}
return self;
}
@end
複製代碼
kCMkvoAssiociateObserver_for_Block
來獲取這個「屬性」觀察者數組(這個其實並非真正意義的屬性,屬於runtime關聯對象的知識範疇,可理解成 觀察者數組 這樣一個屬性)。其中,關於(__bridge void *)
的知識後面會講到。調用者:利用上面的API爲被觀察者添加KVO
#import "NSObject+Block_KVO.h"
//...........
- (void)viewDidLoad {
[super viewDidLoad];
ObservedObject * object = [ObservedObject new];
object.observedNum = @8;
#pragma mark - Observed By Block
[object CM_addObserver: self forKey: @"observedNum" withBlock: ^(id observedObject, NSString *observedKey, id oldValue, id newValue) {
NSLog(@"Value had changed yet with observing Block");
NSLog(@"oldValue---%@",oldValue);
NSLog(@"newValue---%@",newValue);
}];
object.observedNum = @10;
}
複製代碼
【API註解①】:object_setClass
咱們能夠在運行時建立新的class,這個特性用得很少,但其實它仍是很強大的。你能經過它建立新的子類,並添加新的方法。
但這樣的一個子類有什麼用呢?別忘了Objective-C的一個關鍵點:object內部有一個叫作isa的變量指向它的class。這個變量能夠被改變,而不須要從新建立。而後就能夠添加新的ivar和方法了。能夠經過如下命令來修改一個object的class
object_setClass(myObject, [MySubclass class]);
複製代碼
這能夠用在Key Value Observing。當你開始observing an object時,Cocoa會建立這個object的class的subclass,而後將這個object的isa指向新建立的subclass。
【API註解②】:objc_allocateClassPair
objc_allocateClassPair(Class _Nullable superclass, const char * _Nonnull name,
size_t extraBytes)
複製代碼
objc_allocateClassPair
). 二、爲建立的類添加方法和成員(上例使用class_addMethod
添加了一個方法)。 三、註冊你建立的這個類,使其可用(使用objc_registerClassPair
)。爲何這裏1和3都說到pair,咱們知道pair的中文意思是一對,這裏也就是一對類,那這一對類是誰呢?他們就是Class、MetaClass。
【API註解③】:(__bridge void *)
在 ARC 有效時,經過 (__bridge void *)
轉換 id 和 void * 就可以相互轉換。爲何轉換?這是由於objc_getAssociatedObject
的參數要求的。先看一下它的API:
objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)
複製代碼
能夠知道,這個「屬性名」的key是必須是一個void *
類型的參數。因此須要轉換。關於這個轉換,下面給一個轉換的例子:
id obj = [[NSObject alloc] init];
void *p = (__bridge void *)obj;
id o = (__bridge id)p;
複製代碼
關於這個轉換能夠了解更多:ARC 類型轉換:顯示轉換 id 和 void *
固然,若是不經過轉換使用這個API,就須要這樣使用:
objc_getAssociatedObject(self, @"AddClickedEvent");
複製代碼
static const void *registerNibArrayKey = ®isterNibArrayKey;
複製代碼
NSMutableArray *array = objc_getAssociatedObject(self, registerNibArrayKey);
複製代碼
static const char MJErrorKey = '\0';
複製代碼
objc_getAssociatedObject(self, &MJErrorKey);
複製代碼
+ (instancetype)cachedPropertyWithProperty:(objc_property_t)property
{
MJProperty *propertyObj = objc_getAssociatedObject(self, property);
//省略
}
複製代碼
其中objc_property_t
是runtime的類型
typedef struct objc_property *objc_property_t;
複製代碼
剩下的就是runtime的比較常見API了,這裏就不按照上面代碼的順序的講解了。這裏只作按runtime的知識範疇將這些API作一個分類:
objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)
objc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key,
id _Nullable value, objc_AssociationPolicy policy)
複製代碼
BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types);
object_getClass(id _Nullable obj)
Method class_getInstanceMethod(Class cls, SEL name);
const char * method_getTypeEncoding(Method m);
FOUNDATION_EXPORT SEL NSSelectorFromString(NSString *aSelectorName);
複製代碼
objc_msgSendSuper
複製代碼
- (void)willChangeValueForKey:(NSString *)key;
- (void)didChangeValueForKey:(NSString *)key;
複製代碼
注意:如下都是同一個文件:NSObject+Block_Delegate.m中寫的
@interface CM_ObserverInfo : NSObject
@property (nonatomic, weak) NSObject * observer;
@property (nonatomic, copy) NSString * key;
//修改這裏
@property (nonatomic, assign) id <ObserverDelegate> observerDelegate;
@end
複製代碼
@implementation CM_ObserverInfo
- (instancetype)initWithObserver: (NSObject *)observer forKey: (NSString *)key
{
if (self = [super init]) {
_observer = observer;
self.key = key;
//修改這裏
self.observerDelegate = (id<ObserverDelegate>)observer;
}
return self;
}
@end
複製代碼
#pragma mark -- NSObject Category(KVO Reconstruct)
@implementation NSObject (Block_KVO)
- (void)CM_addObserver:(NSObject *)observer forKey:(NSString *)key withBlock:(CM_ObservingHandler)observedHandler
{
//...省略
//add this observation info to saved new observer
//修改這裏
CM_ObserverInfo * newInfo = [[CM_ObserverInfo alloc] initWithObserver: observer forKey: key];
//...省略
}
複製代碼
調用者:利用上面的API爲被觀察者添加KVO
#import "NSObject+Delegate_KVO.h"
//...........
- (void)viewDidLoad {
[super viewDidLoad];
ObservedObject * object = [ObservedObject new];
object.observedNum = @8;
#pragma mark - Observed By Delegate
[object CM_addObserver: self forKey: @"observedNum"];
object.observedNum = @10;
}
複製代碼
#pragma mark - ObserverDelegate
-(void)CM_ObserveValueForKeyPath:(NSString *)keyPath ofObject:(id)object oldValue:(id)oldValue newValue:(id)newValue{
NSLog(@"Value had changed yet with observing Delegate");
NSLog(@"oldValue---%@",oldValue);
NSLog(@"newValue---%@",newValue);
}
複製代碼
筆者另外寫了runtime的原理與實踐。若是想了解runtime的更多知識,能夠選擇閱讀這些文章: