Swift利用协议优化NSNotificationCenter之添加Block

代码参考! 下面的源码基于这个 添加了Block模式,方便调用

源码

private class STObserversManager: NSObject {

    static let sharedInstance = STObserversManager()

    private var _observers = [(AnyObject, String, NSObjectProtocol)]()

    func add(observer: AnyObject, name: String, obj: NSObjectProtocol) {
        let arr = _observers.filter({$0.0 === observer && $0.1 == name})
        if arr.count > 0 {
            return
        }
        _observers.append((observer, name, obj))
    }

    func exist(observer: AnyObject, name: String? = nil) -> Bool {
        return observers(observer, name: name).count > 0
    }

    func observers(observer: AnyObject, name: String? = nil) -> [(AnyObject, String, NSObjectProtocol)] {
        return _observers.filter({name != nil ? $0.0 === observer && $0.1 == name : $0.0 === observer})
    }

    func removeAll(observer: AnyObject) {
        for i in (0..<_observers.count).reverse() {
            if _observers[i].0 === observer {
                _observers.removeAtIndex(i)
            }
        }
    }

}

public protocol STNotifier {

    associatedtype NotificationKey: RawRepresentable

}

// MARK: - 定义MTNotifier的方法
public extension STNotifier where NotificationKey.RawValue == String {

    private static func nameFor(notification: NotificationKey) -> String {
        return "\(self).\(notification.rawValue)"
    }

    func postNotification(notification: NotificationKey, object: AnyObject? = nil) {
        Self.postNotification(notification, object: object)
    }

    func postNotification(notification: NotificationKey, object: AnyObject? = nil, userInfo: [String : AnyObject]? = nil) {
        Self.postNotification(notification, object: object, userInfo: userInfo)
    }

    static func postNotification(notification: NotificationKey, object: AnyObject? = nil, userInfo: [String : AnyObject]? = nil) {
        let name = nameFor(notification)

        NSNotificationCenter.defaultCenter()
            .postNotificationName(name, object: object, userInfo: userInfo)
    }

    static func addObserver(observer: AnyObject, notification: NotificationKey, block: (notification: NSNotification) -> Void) {
        let name = nameFor(notification)
        if STObserversManager.sharedInstance.exist(observer, name: name) {
            NSLog("observer is exist")
        } else {
            let obj = NSNotificationCenter.defaultCenter()
                .addObserverForName(name, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: block)
            STObserversManager.sharedInstance.add(observer, name: name, obj: obj)
        }
    }

    static func addObserver(observer: AnyObject, selector: Selector, notification: NotificationKey) {
        let name = nameFor(notification)

        NSNotificationCenter.defaultCenter()
            .addObserver(observer, selector: selector, name: name, object: nil)
    }

    static func removeObserver(observer: AnyObject, notification: NotificationKey, object: AnyObject? = nil) {
        let name = nameFor(notification)

        NSNotificationCenter.defaultCenter()
            .removeObserver(observer, name: name, object: object)
    }

    static func removeObservers(observer: AnyObject?) {
        if let observer = observer {
            for observer in STObserversManager.sharedInstance.observers(observer) {
                NSNotificationCenter.defaultCenter().removeObserver(observer.2)
            }
            STObserversManager.sharedInstance.removeAll(observer)
        }
    }

}

##如何调用

创建对象

首先继承STNotifier

class MTMYNTNotifier: STNotifier {

    enum NotificationKey: String {
        case aaa
        case bbb
    }

}

添加监听

MTMYNTNotifier.addObserver(self, notification: .aaa) { (notification) in
  NSLog("....notification...aaa...")
}

发送消息

MTMYNTNotifier.postNotification(.aaa)

移除监听

MTMYNTNotifier.removeObservers(self)
坚持原创技术分享,您的支持将鼓励我继续创作!