Swift - 优雅的实现通知-发送、接收、移除

2017-01-14 10:45:20来源:http://www.jianshu.com/p/0236b1d2d46d作者:逗牛人点击

第七城市

Swift优雅的使用通知NSNotification


SnailNotice.swift
   import UIKit
protocol Notifier {
associatedtype Notification: RawRepresentable
}
extension Notifier where Notification.RawValue == String {
static func nameFor(notification: Notification) -> String {
return "/(notification.rawValue)"
}
}
class SnailNotice: Notifier {
/// 发送通知
static func post(notification: Notification, object:AnyObject? = nil) {
let name = nameFor(notification: notification)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: name), object: object)
}
/// 增加观察 - 接收通知
static func add(observer: AnyObject, selector: Selector, notification: Notification, object:AnyObject? = nil) {
let name = nameFor(notification: notification)
NotificationCenter.default
.addObserver(observer, selector: selector, name: NSNotification.Name(rawValue: name), object: object)
}
/// 移除观察 - 移除通知
static func remove(observer: AnyObject, notification: Notification, object:AnyObject? = nil) {
let name = nameFor(notification: notification)
NotificationCenter.default.removeObserver(observer, name: NSNotification.Name(rawValue: name), object: object)
}
}
// 定义的通知名字
extension SnailNotice {
enum Notification: String {
/// 开心
case happy
/// 伤心
case sad
/// 睡觉
case sleep
/// ....
case
第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台