美文网首页
Swift通知中心使用技巧

Swift通知中心使用技巧

作者: Seacen_Liu | 来源:发表于2018-05-29 22:23 被阅读0次

通知中心是一套基于字符串的松散 API,用于实现一对多的消息传递,可以实现跨页面的传递。但在使用起来的时候有些繁琐,而且通知多起来也不好管理。在学习过程中,学到了一种比较适合Swift的通知写法。通过扩展和泛型的方式,构成一套类型安全的通知中心使用方式。

代码如下:

extension Notification {
    struct UserInfoKey<ValueType>: Hashable {
        let key: String
    }
    
    /// 直接获取相应的值
    func getUserInfo<T>(for key: Notification.UserInfoKey<T>) -> T {
        return userInfo![key] as! T
    }
}

extension NotificationCenter {
    /// 用于发送带有[Notification.UserInfoKey<T> : T]的通知
    func post<T>(name aName: NSNotification.Name, object anObject: Any?, typedUserInfo aUserInfo: [Notification.UserInfoKey<T> : T]? = nil) {
        post(name: aName, object: anObject, userInfo: aUserInfo)
    }
}

extension Notification.Name {
    static let <#通知名称#> = Notification.Name(rawValue: "<#表示特定通知的唯一字符串#>")
    // ...
}

extension Notification.UserInfoKey {
    static var recordStoreAnnotationsDidChangedBehaviorKey: Notification.UserInfoKey<<#类型#>> {
        return Notification.UserInfoKey(key: <#表示传递信息的键的唯一字符串#>)
    }
    // ...
}

使用这种方案处理的通知,在发送通知和获取通知中的值的时候十分便利和舒服。
摘自王巍的Demo中的代码,特地写出来,以供自己加深体会Swifty的写法。

相关文章

网友评论

      本文标题:Swift通知中心使用技巧

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