LoginSignup
2
1

More than 5 years have passed since last update.

[Swift] Notificationの管理を楽チンにする

Last updated at Posted at 2018-01-11

Swift4 にてNotificationのobserverの追加に関数を渡せるバージョンができてかなりわかりやすくなりました。

が、addObserver(forName:object:queue:using:)の戻り値を確保しておく必要があり、非常に面倒くさいです。


class Hoge {

    var observing: [NSObjectProtocol]

    init() {

        let o0 = NotificationCenter.default.addObserver(forName: NSView.frameDidChangeNotification, queue: nil, object: nil) {

            print("observe", $0)
        }
        observing += [o0]

        let o1 = NotificationCenter.default.addObserver(forName: NSView.didUpdateTrackingAreasNotification, queue: nil, object: nil) {

            print("observe", $0)
        }
        observing += [o1]

       // まだまだつづくよー
    }

    deinit {
        observing.map(NotificationCenter.default.removeObserver)
    }
}

すごくアホっぽいです。

なので、アホっぽさを隠してみました。

/// 開放時にremoveObserver(_:)を実行してくれるクラス
class NotificationObserver {

    private var observer: [NSObjectProtocol] = []

    func addObserver(forName name: Notification.Name, object: Any?, queue: OperationQueue? = nil, using block: @escaping (Notification) -> Void) {

        observer += [NotificationCenter.default.addObserver(forName: name, object: object, queue: queue, using: block)]
    }

    deinit {
        observer.map(NotificationCenter.default.removeObserver)
    }
}

使用法

class Hoge {

    let observer = NotificationObserver()

    init() {

        observer.addObserver(forName: NSView.frameDidChangeNotification, object: nil) {

            print("observe", $0)
        }

        observer.addObserver(forName: NSView.didUpdateTrackingAreasNotification, object: nil) {

            print("observe", $0)
        }
    }
}

スッキリ!

2
1
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
2
1