美文网首页
swift类型化通知

swift类型化通知

作者: 豆晓 | 来源:发表于2018-08-05 12:45 被阅读0次

    为什么要类型化通知?

    在重构工程的时候,发现工程中使用Notification API的地方非常多,notification的使用充满了各种硬编码,例:

    extension Notification.Name {
        static let test = Notification.Name.init("com.typedNotification.test")
    }
    NotificationCenter.default.post(name: .test, object: nil, userInfo: ["passedNum": 1, "passedString": "it is boring"])
    

    在一个通知中,可能会携带object或userInfo,在接收端的代码:

    notiToken = NotificationCenter.default.addObserver(forName: .test, object: nil, queue: nil) { (noti) in
        guard let num = noti.userInfo?["passed"] as? Int, let str = noti.userInfo?["passedString"] as? String else {
            return
        }
        print("\(num) \(str)")
    }
    

    同时还需要在通知不用的时候remove

    NotificationCenter.default.removeObserver(notiToken)
    

    这样会导致每当我们需要post和接收test通知的时候,都需要写上面那样的代码。假如需要修改“passed”的类型或者增加一个传递的参数,那就需要找到每一处发送和接收test通知的地方进行修改,这样维护起来就非常艰难了,所以需要改写这些通知的使用方式。

    如何类型化通知?

    • 首先定义一个通知发送描述协议
    protocol NotificationDescriptor {
        var name: Notification.Name { get }
        var userInfo:[AnyHashable: Any]? { get }
        var object: Any? { get }
    }
    
    extension NotificationDescriptor {
        var userInfo:[AnyHashable: Any]? {
            return nil
        }
        var object: Any? {
            return nil
        }
    }
    
    extension NotificationDescriptor {
        func post(on center: NotificationCenter = NotificationCenter.default) {
            center.post(name: name, object: object, userInfo: userInfo)
        }
    }
    
    
    • 定义一个接收解析通知的类型
    protocol NotificationDecodable {
        init(_ notification: Notification)
    }
    
    extension NotificationDecodable {
        static func observer(on center: NotificationCenter = NotificationCenter.default ,
                      for aName: Notification.Name,
                      using block: @escaping (Self) -> Swift.Void) -> NotificationToken {
            let token = center.addObserver(forName: aName, object: nil, queue: nil, using: {
                block(Self.init($0))
            })
            return NotificationToken.init(token, center: center)
        }
    }
    
    • 我们还希望能把通知的发送和解析逻辑写在一起
    typealias TypedNotification = NotificationDescriptor & NotificationDecodable
    

    这样test通知可以写成这样:

    struct TestNotificaiton: TypedNotification {
        var name: Notification.Name { return .test }
        var userInfo: [AnyHashable : Any]? {
            return ["passedNum": num, "passedStr": str]
        }
        var num: Int
        var str: String
        init(_ notification: Notification) {
            num = notification.userInfo!["passedNum"] as! Int
            str = notification.userInfo!["passedStr"] as! String
        }
        init(_ num: Int, str: String) {
            self.num = num
            self.str = str
        }
    }
    
    • 发送通知:
    let testDescriptor = TestNotificaiton.init(1, str: "it is fine")
    testDescriptor.post()
    
    • 接受通知:
    notiToken = TestNotificaiton.observer(for: .test) { (testObj) in
        print("\(testObj.num) \(testObj.str)")
    }
    

    notiToken类似于NSKeyValueObservation, 并不需要手动去移除通知,管理notiToken的生命周期就可以了。

    通过类型化通知,把通知的发送的描述和接收的解析处理写在一起,有利于后期的持续维护,具体实现我单独拿出来放到了这个repo中, 有兴趣的可以去看看。

    注意

    通知在MVC中是一个非常重要的机制。但是使用通知需要谨慎,如果过度使用通知,对象之间会产生各种错综复杂的依赖,非常不利于工程的拆分。

    相关文章

      网友评论

          本文标题:swift类型化通知

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