swift类型化通知

为什么要类型化通知?

在重构工程的时候,发现工程中使用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中是一个非常重要的机制。但是使用通知需要谨慎,如果过度使用通知,对象之间会产生各种错综复杂的依赖,非常不利于工程的拆分。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 30,393评论 8 265
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,047评论 19 139
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,807评论 1 32
  • 万能钥匙意指解决所有问题的通用方法,即问题只是事物的表象,不要只盯着问题打转,解决问题的方法在别处。 万能钥匙属于...
    _德成阅读 346评论 0 2
  • 作家林清玄写过两句话:“快乐地活在当下,尽心即是完美。”他也是学禅之人,他说禅的解释是这样的:禅左边是“表示”的“...
    原圆阅读 917评论 0 3

友情链接更多精彩内容