ObjC:
删除前使用observerKeyPath判断是否能删除
// 进行检索获取Key
- (BOOL)observerKeyPath:(NSObject*)object :(NSString *)key
{
//判断keyPath有或者无来实现防止多次重复添加和删除KVO监听
id info = object.observationInfo;
NSArray *array = [info valueForKey:@"_observances"];
for (id objc in array) {
id properties = [objc valueForKeyPath:@"_property"];
NSString *keyPath = [properties valueForKeyPath:@"_keyPath"];
if ([key isEqualToString:keyPath]) {
return YES;
}
}
return NO;
}
Swift:
使用objAddObserver添加观察者、使用objRemoveObserver删除
var objKeyArr:Array<(Object:NSObject, Key:String)> = []//储存绑定KVO的数组
func objAddObserver(_ obj:NSObject,_ key:String) {
obj.addObserver(self, forKeyPath: key, options: .new, context: nil)
let aTuple = (Object:obj, Key:key)//使用元组obj-key对应
objKeyArr.append(aTuple)//储存绑定的KVO
}
func objRemoveObserver(_ obj:NSObject,_ key:String) {
guard let remObjIndex = objKeyArr.firstIndex(where: { $0.Object==obj && $0.Key==key}) else { return }//查找obj和key是否已绑定
obj.removeObserver(self, forKeyPath: key)
objKeyArr.remove(at: remObjIndex)
}
网友评论