Swift中Notification.Name這么難用怎么辦

以前的發(fā)送通知的參數(shù)就是一個簡單的字符串:

NSNotificationCenter.defaultCenter().post("someStringThatShouldBeDeclared")

后來到了swift 3 中,改成了Notification.Name。定義在Notification的命名空間下,是一個結(jié)構(gòu)體,初始化函數(shù)接收一個字符串。

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

        public init(_ rawValue: String)

        public init(rawValue: String)
    }
}

用起來就麻煩了一點(diǎn):

NotificationCenter.default.post(Notification.Name(rawValue: "MyNotificationName"))

如果還是按照以前的方式定義一個全局字符串常量就沒有好好領(lǐng)會Swift精神了。

至少需要這樣,通過extension聲明一個靜態(tài)的常量:

extension Notification.Name {
    static let AccountBalanceUpdated = Notification.Name("accountBalanceUpdated")
}
 
// invocation
NotificationCenter.default.post(.AccountBalanceUpdated)

但是這種方式有一個小缺點(diǎn),自定義的通知和系統(tǒng)的混在了一起,有時找起來比較尷尬。



這里其實(shí)也有另外一個問題,這種方式不能避免通知的名字重復(fù)。雖然如果命名規(guī)范不會有這樣的問題,但是到底是個潛在的風(fēng)險。

如果把上面兩個問題合起來看,就有了另外一種方式:利用Enum。
先聲明一個rawValue為字符串的枚舉。為了規(guī)避命名的沖突,聲明一個計算屬性,在每個值的rawValue前插入一個字符串。再用這個字符串去生成NSNotification.Name:

enum CPNotification: String {
    case userLogout
    case userLogin
    
    var stringValue: String {
        return "CP" + rawValue
    }
    
    var notificationName: NSNotification.Name {
        return NSNotification.Name(stringValue)
    }  
}

用起來就簡單了,自己寫一個擴(kuò)展方法:

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

這樣在使用時,直接點(diǎn)出來的就都是自定義的通知了。
當(dāng)然在通知處理的地方也寫個擴(kuò)展方法用起來就更爽了,比如我用Rx所以這樣寫:

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

用起來就是這樣:

       // 發(fā)送通知
        NotificationCenter.post(customeNotification: .userLogout)
    
      // 接收通知
       let _ = NotificationCenter.default.rx.notification(custom: .userLogout).subscribe(onNext: { (value) in
            CPNetworkConfig.userID = nil
        })

歡迎在社交網(wǎng)絡(luò)上關(guān)注我:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,176評論 4 61
  • 關(guān)于 Swift 重要這個文檔所包含的準(zhǔn)備信息, 是關(guān)于開發(fā)的 API 和技術(shù)的。這個信息可能會改變, 根據(jù)這個文...
    無灃閱讀 4,607評論 1 27
  • title: "Swift 中枚舉高級用法及實(shí)踐"date: 2015-11-20tags: [APPVENTUR...
    guoshengboy閱讀 2,690評論 0 2
  • 向90后賣故事,向80后賣情感,向75后賣服務(wù),向70后賣檔次,向65后賣質(zhì)量,向60后賣份量,55后及再前面的人...
    方小文閱讀 345評論 0 4
  • 素質(zhì)不是你把飲料瓶扔進(jìn)垃圾箱就算素質(zhì),那是最基本的修養(yǎng)好伐?真正的素質(zhì),《歡樂頌》里劉濤最的一句話一言中的#只與同...
    臻靜閱讀 601評論 1 1

友情鏈接更多精彩內(nèi)容