KVO是IOS中非常常用的一個東西服鹅,也是相當好用的权埠。
但是常常在用的時候由于觀察者和觀察屬性的增加,導致我們并不知道對象是否已經監(jiān)聽,造成的結果就是重復監(jiān)聽或者移除沒有監(jiān)聽的屬性蚀浆,前者可能產生邏輯問題,后者之程序將會crash掉搜吧。
其實按道理說市俊,如果我們養(yǎng)成一個良好的KVO習慣的話是不會造成這種問題的,
比如 http://stackoverflow.com/questions/9231896/kvo-how-to-check-if-an-object-is-an-observer 中就有提到滤奈,如果
有良好的習慣去寫KVO的話摆昧,是可以避免這種問題的,但是蜒程,難免當屬性和對象增多的時候绅你,腦子就不好使了,所以昭躺,希望用一個一勞永逸的辦法去避免這種事情的發(fā)生忌锯。
然后找到了這個屬性 var observationInfo: UnsafeMutablePointer<Void>
The observationInfo is a pointer that identifies information about all of the observers that are registered with the receiver. The default implementation of this method stores observationInfo in a global dictionary keyed by the receiver’s pointers.
For improved performance, this method and observationInfo can be overridden to store the opaque data pointer in an instance variable. Classes that override this method must not attempt to send Objective-C messages to observationInfo, including retain and release
在OBJC下,把他print出來
id *a = self.apple.observationInfo;
NSLog(@"%@",a);
<NSKeyValueObservationInfo 0x100204d60> (
<NSKeyValueObservance 0x100105630: Observer: 0x100101900, Key path: name, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x100104070>
<NSKeyValueObservance 0x100204470: Observer: 0x100101900, Key path: age, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x100201eb0>
<NSKeyValueObservance 0x100204a50: Observer: 0x100103980, Key path: age, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x100201eb0>
)
observationInfo指針實際上是指向一個NSKeyValueObservationInfo對象领炫,它包含了指定對象上的所有的監(jiān)聽信息偶垮。而每條監(jiān)聽信息而是封裝在一個NSKeyValueObservance對象中。
看到這帝洪,一想太好了似舵,我只要重新寫AddObserve方法,每次Add或者remove的時候進行一次判斷就可以了葱峡,然而NSKeyValueObservationInfo類及NSKeyValueObservance類都是私有類砚哗,我們根本沒辦法拿到這個對象,只能Debug的時候用砰奕,所以這條路已經死了蛛芥。
在這片文章中 http://www.bkjia.com/IOSjc/993206.html#comment 作者dump出了類結構
#import <XXUnknownSuperclass.h>
// Unknown library@class NSArray, NSHashTable;__attribute__((visibility("hidden")))
@interface NSKeyValueObservationInfo : XXUnknownSuperclass
{
@private int _retainCountMinusOne;
NSArray* _observances; unsigned _cachedHash;
BOOL _cachedIsShareable; NSHashTable* _observables;
}
-(id)_initWithObservances:(id*)observances count:(unsigned)count;
-(id)retain;-(oneway void)release;
-(unsigned)retainCount;-(void)dealloc;
-(unsigned)hash;
-(BOOL)isEqual:(id)equal;
-(id)description;@end
@class NSPointerArray, NSKeyValueProperty, NSObject;__attribute__((visibility("hidden")))
@interface NSKeyValueObservance : XXUnknownSuperclass
{
@private int _retainCountMinusOne;
NSObject* _observer;
NSKeyValueProperty* _property;
unsigned _options; void* _context;
NSObject* _originalObservable;
unsigned _cachedUnrotatedHashComponent;
BOOL _cachedIsShareable;
NSPointerArray* _observationInfos;
auto_weak_callback_block _observerWentAwayCallback;
}
-(id)_initWithObserver:(id)observer property:(id)property options:(unsigned)options context:(void*)context originalObservable:(id)observable;
-(id)retain;-(oneway void)release;
-(unsigned)retainCount;
-(void)dealloc;
-(unsigned)hash;
-(BOOL)isEqual:(id)equal;
-(id)description;
-(void)observeValueForKeyPath:(id)keyPath ofObject:(id)object change:(id)change context:(void*)context;
@end
同時也有講到
The default implementation of this method retrieves the information from a globaldictionary keyed by the receiver’s pointers.
即這個方法的默認實現是以對象的指針作為key提鸟,從一個全局的字典中獲取信息。由此仅淑,我們可以理解為称勋,KVO的信息是存儲在一個全局字典中,而不是存儲在對象本身漓糙。這類似于Notification,所有關于通知的信息都是放在NSNotificationCenter中烘嘱。
不過昆禽,為了提高效率,我們可以重寫observationInfo屬性的set和get方法蝇庭,以將這個不透明的數據指針存儲到一個實例變量中醉鳖。但是,在重寫時哮内,我們不應該嘗試去向這些數據發(fā)送一個Objective-C消息盗棵,包括retain和release。
最終找到一個解決辦法就是北发,擴展nsobject纹因,自定add和remove方法,通過一個存儲數組來保存已經監(jiān)聽的屬性和對象琳拨。
extension NSObject {
private struct associatedKeys {
static var safe_observersArray = "observers"
}
private var observers: [[String : NSObject]] {
get {
if let observers = objc_getAssociatedObject(self, &associatedKeys.safe_observersArray) as? [[String : NSObject]] {
return observers
} else {
self.observers = [[String : NSObject]]()
return observers
}
} set {
objc_setAssociatedObject(self, &associatedKeys.safe_observersArray, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public func safe_addObserver(observer: NSObject, forKeyPath keyPath: String) {
let observerInfo = [keyPath : observer]
if observers.indexOf({ $0 == observerInfo }) == nil {
observers.append(observerInfo)
addObserver(observer, forKeyPath: keyPath, options: .New, context: nil)
}
}
public func safe_removeObserver(observer: NSObject, forKeyPath keyPath: String) {
let observerInfo = [keyPath : observer]
if let index = observers.indexOf({ $0 == observerInfo}) {
observers.removeAtIndex(index)
removeObserver(observer, forKeyPath: keyPath)
}
}
}
不過我覺得瞭恰,如果是需要監(jiān)聽自己的屬性的話,應該自己在Set方法里面手動去監(jiān)聽狱庇,