LoginSignup
9
6

More than 5 years have passed since last update.

NSNotificationをシンプルに書く方法

Posted at

概要

NSNotificationをpostしたりaddObserver/removeObserverする際、NSNotification.Nameに文字列を指定するとタイプミスをすると、正しく動作しなくなってしまいます。しかし、ビルドは通るため、気づくのに時間がかかってしまいます。そこで、NSNotification.Nameを拡張し、独自のnameを定義します。

1. NSNotification.Name拡張

独自のnameを定義します。

extension NSNotification.Name {
    static let sample = Notification.Name(rawValue: "sample")
//    static let hoge = Notification.Name(rawValue: "hoge")
//    static let fuga = Notification.Name(rawValue: "fuga")
}

2. 通知発行コード

NotificationCenter.default.post(name: .sample, object: nil)

3. 通知受信側コード

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
         object: nil)

        NotificationCenter.default.addObserver(self, selector: #selector(onSampleNotified(_:)), name: .sample, object: nil)
    }

    deinit {
        NotificationCenter.default.removeObserver(self, name: .sample, object: nil)
    }

    func onSampleNotified(_ notification: NSNotification) {
        print("Notification button pushed")
    }
}

サンプル

Notification-Name@githubに動作するプロジェクトがあります。

9
6
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
9
6