Swiftでいい感じにNSNotificationCenter#addObserverForNameを使う
NSNotificationCenterの事は嫌いじゃないんだけどaddObserver:selector:name:object:とaddObserverForNameがどちらも一長一短でもどかしくラッパーを書きました。
どういう一長一短かというと
addObserverForName | removeObserverが面倒臭い | addする側でQueueが指定できる |
addObserver:selector:name:object: | removeObserverが楽 | post時のスレッドで動作する |
書きたかったコード。
// UI弄るやつ Notification.onMainThread(self, name:"changeData", handler: { }) // UI弄らないやつ Notification.onBackgroundThread(self, name:"changeData", handler: { }) // on時にselfを指定して登録したすべてのobserverをremove Notification.off(self) // イベント発行 Notification.post("changeData")
before
var observers = [NSObjectProtocol]() override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let observer = NSNotificationCenter.defaultCenter().addObserverForName("changeData", object: nil, queue: nil, usingBlock: { (notification: NSNotification!) in self.reload() }) observers.append(observer) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) for observer in observers { NSNotificationCenter.defaultCenter().removeObserver(observer) } observers = [NSObjectProtocol]() }
after
override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) Notification.onMainThread(self, name:"changeData", handler: { _ in self.reload() }) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) Notification.off(self) }