LoginSignup
19
19

More than 5 years have passed since last update.

Notificationの登録を簡単にするextension

Last updated at Posted at 2015-02-23

Notification登録がだるくてかつけっこうミスりそうなので良い感じのextension作ってみた( ´・‿・`)

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()
19
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
19