Swift中Notification.Name这么难用怎么办

以前的发送通知的参数就是一个简单的字符串:

NSNotificationCenter.defaultCenter().post("someStringThatShouldBeDeclared")复制代码

后来到了swift 3 中,改成了Notification.Name。定义在Notification的命名空间下,是一个结构体,初始化函数接收一个字符串。

extension NSNotification {
    public struct Name : RawRepresentable, Equatable, Hashable, Comparable {

        public init(_ rawValue: String)

        public init(rawValue: String)
    }
}复制代码

用起来就麻烦了一点:

NotificationCenter.default.post(Notification.Name(rawValue: "MyNotificationName"))复制代码

如果还是按照以前的方式定义一个全局字符串常量就没有好好领会Swift精神了。

至少需要这样,通过extension声明一个静态的常量:

extension Notification.Name {
    static let AccountBalanceUpdated = Notification.Name("accountBalanceUpdated")
}

// invocation
NotificationCenter.default.post(.AccountBalanceUpdated)复制代码

但是这种方式有一个小缺点,自定义的通知和系统的混在了一起,有时找起来比较尴尬。


这里其实也有另外一个问题,这种方式不能避免通知的名字重复。虽然如果命名规范不会有这样的问题,但是到底是个潜在的风险。

如果把上面两个问题合起来看,就有了另外一种方式:利用Enum。
先声明一个rawValue为字符串的枚举。为了规避命名的冲突,声明一个计算属性,在每个值的rawValue前插入一个字符串。再用这个字符串去生成NSNotification.Name:

enum CPNotification: String {
    case userLogout
    case userLogin

    var stringValue: String {
        return "CP" + rawValue
    }

    var notificationName: NSNotification.Name {
        return NSNotification.Name(stringValue)
    }  
}复制代码

用起来就简单了,自己写一个扩展方法:

extension NotificationCenter {
    static func post(customeNotification name: CPNotification, object: Any? = nil){
        NotificationCenter.default.post(name: name.notificationName, object: object)
    }
}复制代码

这样在使用时,直接点出来的就都是自定义的通知了。
当然在通知处理的地方也写个扩展方法用起来就更爽了,比如我用Rx所以这样写:

extension Reactive where Base: NotificationCenter {

    func notification(custom name: CPNotification, object: AnyObject? = nil) -> Observable<Notification> {
       return notification(name.notificationName, object: object)
    }

}复制代码

用起来就是这样:

       // 发送通知
        NotificationCenter.post(customeNotification: .userLogout)

      // 接收通知
       let _ = NotificationCenter.default.rx.notification(custom: .userLogout).subscribe(onNext: { (value) in
            CPNetworkConfig.userID = nil
        })复制代码

欢迎在社交网络上关注我:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值