Skip to content

Instantly share code, notes, and snippets.

@mono0926
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mono0926/28966ea7a7bfcb4ad7c7 to your computer and use it in GitHub Desktop.
Save mono0926/28966ea7a7bfcb4ad7c7 to your computer and use it in GitHub Desktop.
Notificationの登録を簡単にするextension ref: http://qiita.com/mono0926/items/e3a76dc95046f0eeeb29
extension UIViewController {
// こんな感じの公開メソッドを増やしていく
func observeKeyboard(willShowSelector: Selector, willHideSelector: Selector) -> () -> () {
return observeNotification([
(action: willShowSelector, name: UIKeyboardWillShowNotification),
(action: willHideSelector, name: UIKeyboardWillHideNotification)])
}
func observeDidBecomeActive(action: Selector) -> () -> () {
return observeNotification(action, name: UIApplicationDidBecomeActiveNotification)
}
// あるいはこちらを公開して直に使っちゃっても良いかも
private func observeNotification(action: Selector, name: String) -> () -> () {
return observeNotification([(action: action, name: name)])
}
private func observeNotification(pairs: [(action: Selector, name: String)]) -> () -> () {
for p in pairs {
NSNotificationCenter.defaultCenter().addObserver(self, selector: p.action, name: p.name, object: nil)
}
return { [unowned self] in // これ忘れるとメモリリークするので注意
for p in pairs {
return NSNotificationCenter.defaultCenter().removeObserver(self, name: p.name, object: nil)
}
}
}
}
// ViewControllerのappear系で登録
removeObserverClosure = observeDidBecomeActive("didBecomeActive:")
// ViewControllerのdisappear系で登録解除
removeObserverClosure()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment