LoginSignup
1
1

More than 5 years have passed since last update.

[Swift] Notificationを一回だけObserveするよ!

Posted at

たまに1回だけNotificationを受けたいということがあるのでextensionを作ったよ。

extension NotificationCenter {

    func addObserverOnce(forName name: NSNotification.Name?, object obj: Any?, queue: OperationQueue?, using block: @escaping (Notification) -> Void) {

        weak var token: NSObjectProtocol?
        token = addObserver(forName: name, object: obj, queue: queue) {notification in

            token.map(self.removeObserver)
            block(notification)
        }
    }
}

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