利用NSObject实现观察者模式(KVO模式)

类定义

class huofu:NSObject
{
    dynamic var danchaofan = ""
    func update(status:String)
    {
        danchaofan = status
    }
}
class xiaohuoban:NSObject {
    init(objectToObserver:AnyObject) {
        super.init()
        //添加传递进来的类的观察者
        objectToObserver.addObserver(self, forKeyPath: "danchaofan", options: .New, context: &myContext)
    }
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]!, context: UnsafeMutablePointer<Void>) {
        if context == &myContext
        {
            print("\(change![NSKeyValueChangeNewKey])")
        }
    }
}

运行代码

let chaoge:huofu = huofu()
let huoban:xiaohuoban = xiaohuoban(objectToObserver: chaoge)
chaoge.update("更新1")
chaoge.removeObserver(huoban, forKeyPath: "danchaofan")

上面这样,可以正常运行,输出是正确的,但是之后会报错

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x7fdad1c0d270 of class CoreDataTest.huofu was deallocated while key value observers were still registered with it. Current observation info:

大概就是因为被观察的已经被回收了,但是观察者依然存在
改成下面就ok了

let chaoge:huofu = huofu()
let huoban:xiaohuoban = xiaohuoban(objectToObserver: chaoge)
chaoge.update("更新1")
chaoge.removeObserver(huoban, forKeyPath: "danchaofan")

标签: swift

添加新评论