Swift通知的使用方式

Swift Notification

这里我们先大概梳理下普通通知的使用方式:

  1. 注册监听
override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(test(_ :)), name: NSNotification.Name(rawValue: "TESTNOTIFY"), object: "the object content")
}
  1. 实现监听后执行的方法
func test(_ notify: Notification) {
        print(notify.object ?? "nil")
}
  1. 发送通知
NotificationCenter.default.post(name: Notification.Name(rawValue: "TESTNOTIFY"), object: "hello")

问题

大家会发现监听的时候实际是做了两步,代码比较分散,不容易管理. 这个也正是ZRNotify能帮我们解决的部分

pod方式安装

pod 'ZRNotify', '~> 0.0.5'

使用

调用方式一: 分开监测

lazy var zrNotify: ZRNotify = {
    var zrnotify = ZRNotify()
    zrnotify.on("ScheduleA", notify: { notify in
        
        print(notify.object ?? "nil object")
    }).on("ScheduleB", notify: { notify in
        
        print(notify.object ?? "nil object")
    }).on("ScheduleC", notify: { notify in
        
        print(notify.object ?? "nil object")
    })
    
    return zrnotify
 }()

调用方式二: 统一监测

lazy var zrNotifys: ZRNotify = {
    var zrnotify = ZRNotify()
    zrnotify.ons(["Schedule1", "Schedule2", "Schedule3"], notify: { notify in
        
        print(notify.object ?? "nil object")
    })
    
    return zrnotify
}()

初始化通知接收

override func viewDidLoad() {
    super.viewDidLoad()
    
    // 初始化
    zrNotify.opStatusForAll(true)
    zrNotifys.opStatusForAll(true)
    
    // 测试
    NotificationCenter.default.post(name: Notification.Name(rawValue: "ScheduleA"), object: "hello ScheduleA")
    NotificationCenter.default.post(name: Notification.Name(rawValue: "ScheduleB"), object: nil)
    NotificationCenter.default.post(name: Notification.Name(rawValue: "ScheduleC"), object: "hello ScheduleC")
    
    // 测试
    NotificationCenter.default.post(name: Notification.Name(rawValue: "Schedule1"), object: "hello Schedule1")
    NotificationCenter.default.post(name: Notification.Name(rawValue: "Schedule2"), object: nil)
    NotificationCenter.default.post(name: Notification.Name(rawValue: "Schedule3"), object: "hello Schedule3")
}

取消监听

zrNotify.remove("ScheduleA")

你可能感兴趣的:(Swift通知的使用方式)