Swift利用KVO监听数组元素的变化

一.概述
KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。

二.使用的步骤
1.注册,指定被观察者和观察的对象

   objectToObserve.addObserver(self, forKeyPath: "contentArray", options: .new, context: &myContext)

2.实现属性变化的回调

  override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if context == &myContext {

       } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }

3.移除观察

   deinit {
        objectToObserve.removeObserver(self, forKeyPath: "contentArray", context: &myContext)
    }

三.完整的代码

@objcMembers class MyObjectToObserve: NSObject {
    dynamic var contentArray = [String]()
}
private var myContext = 0
class PlaySpeechString: NSObject,AVSpeechSynthesizerDelegate {
    static let shared = PlaySpeechString()
    var objectToObserve = MyObjectToObserve()

    // Make sure the class has only one instance
    // Should not init or copy outside
    private override init() {
        super.init()
        objectToObserve.addObserver(self, forKeyPath: "contentArray", options: .new, context: &myContext)
    }
    
    override func copy() -> Any {
        return self // SingletonClass.shared
    }
    
    override func mutableCopy() -> Any {
        return self // SingletonClass.shared
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if context == &myContext {

        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }

    }

    deinit {
        objectToObserve.removeObserver(self, forKeyPath: "contentArray", context: &myContext)
        }
    }

注意:
1.被观察属性所在的类需要用 @objcMembers 关键字修饰 要不会报error
fatal error: Could not extract a String from KeyPath
Swift.ReferenceWritableKeyPath
2.被观察的属性需要用dynamic修饰,否则也无法观察到。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,263评论 30 472
  • 设计模式 1.delegate和notification什么区别,什么情况使用? 2.描述一下KVO和KVC。 K...
    丶逐渐阅读 1,989评论 3 2
  • 一、深复制和浅复制的区别? 1、浅复制:只是复制了指向对象的指针,即两个指针指向同一块内存单元!而不复制指向对象的...
    iOS_Alex阅读 1,463评论 1 27
  • Key-Value Observing机制 知识点介绍 Key-Value Observing (简写为KVO):...
    此生浮华祇盼伊亽阅读 1,243评论 0 3
  • 本文结构如下: Why? (为什么要用KVO) What? (KVO是什么) How? ( KVO怎么用) Mo...
    等开会阅读 1,680评论 1 21