美文网首页
iOS KVO开发-防止remove删除崩溃(Swift/Obj

iOS KVO开发-防止remove删除崩溃(Swift/Obj

作者: 左方 | 来源:发表于2021-07-30 15:12 被阅读0次

    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)
    }
    

    相关文章

      网友评论

          本文标题:iOS KVO开发-防止remove删除崩溃(Swift/Obj

          本文链接:https://www.haomeiwen.com/subject/effcvltx.html