Swift自定义通知中心中的KVO

时间:2019-03-13 06:48:50

标签: swift

使用观察者模式,我试图建立自己的通知中心。

我可以调用作为函数的观察者值的唯一方法似乎是:

observer.value(notification.notificationName, observer.value)

这可能不正确,无需将observer.value传递给observer.value,那么正确的答案是什么?

typealias Observer = (String, Any) -> Void

class MyNotification {
    var notificationName: String
    init(name: String) {
        notificationName = name
    }
}

class MyNotificationCenter {
    // var observers = [Observer]() // using an array here does not work
    var observers = [String: Observer]()

    // given
    // for notification name, the block to be executed when the notification is received
    func addObserver(forName name: String, usingBlock block: @escaping Observer) {
        // add observer to the array
        observers[name] = block
    }

    // given
    func removeObserver(forName name: String) {
        if observers[name] != nil {
            observers[name] = nil
        }
    }

    // not given
    func postNotification(notification: MyNotification) {
        // For each object in the observer array, call its processNotification() method
        for observer in observers {
            observer.value(notification.notificationName, observer.value)
        }
    }
}

class Boss {
    let obs1: Observer = { (name, data) in
        print (name, "HERE")
    }

    init() {
        notification.addObserver(forName: "test", usingBlock: obs1)
    }
}

var notification = MyNotificationCenter()
let boss = Boss()
notification.postNotification(notification: MyNotification(name: "test notification"))

问题-在上面的代码中observer.value(notification.notificationName,observer.value)是不正确的,因为绝对不应该将observer.value传递给observer.value,那么该代码的正确解释是什么? / p>

0 个答案:

没有答案