LoginSignup
124
105

More than 3 years have passed since last update.

【Swift】NotificationCenterの使い方

Last updated at Posted at 2018-06-17

今回、あるViewControllerから別のViewControllerに処理を伝搬したいものがあり、
調べたところ、NotificationCenterを使えば実現できると知り実装しました。

今回はその実装方法について説明してみようと思います。

NotificationCenterって??

NotificationCenterは、異なるViewController間のイベント通知を実現できるもので、
発信側と受信側が存在します。

それぞれ、この通知が来たらこの処理をする!
この処理を実行したらあのViewControllerに処理をお願いする!
みたいなことが可能になります。

使い方

通知名前空間の拡張

まず、下記をどこかのファイルに記載してください。
拡張のため、どのファイルに書かないといけないみたいなことはありませんが、
あとから見返してわかる場所に書くことがベストだと思います。

extensions.swift
extension Notification.Name {
    static let notifyName = Notification.Name("notifyName")
}

通知を送りたい側

SendViewController.swift
// 通知を送りたい箇所でこのように記述
NotificationCenter.default.post(name: .notifyName, object: nil)

通知を受け取りたい側

まずはじめに、受け取りたい側のVCでNotificationCenterを登録します。
こうすることで、notifyName通知が発行されたタイミングで、doSomething()が実行されるようになります。

catchViewController.swift
override func viewDidLoad() {
    super.viewDidLoad()
    /// NotificationCenterを登録
    NotificationCenter.default.addObserver(self, selector: #selector(doSomething(notification:)), name: .notifyName, object: nil)
}

注意点

NotificationCenterを登録しっぱなしでは、再度同じ画面を開いた場合、
登録が重複していってしまうため、画面から離れるタイミングでremoveObserverを実行することが重要です。

iOS9.0以降はremoveObserverが不要のようです。
コメントにてご指摘いただきました!
ありがとうございます。
参考サイト Apple公式ドキュメント

catchViewController.swift
NotificationCenter.default.removeObserver(self)

さいごに

これはオブザーバーパターンといわれるもので、
MVVMを使用する場合、使用する頻度が高いんじゃないかなと思います。
値の受け渡しもできるので、私ももう少し勉強を進めていきたいと思います。

では!!

124
105
3

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
124
105