LoginSignup
6
7

More than 3 years have passed since last update.

【Swift】NotificationCenterのuserInfoで値の受け渡しをする

Posted at

はじめに

NotificationCenterで値の受け渡しをする方法を解説します。

実装

import UIKit

final class ViewController: UIViewController {

    @IBOutlet private weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(someFunc), name: .someName, object: nil)
    }

    @objc private func someFunc(notification: Notification) {
        if let num = notification.userInfo?["someKey"] as? Int {
            label.text = String(num)
        }

    }

    @IBAction private func buttonDidTapped(_ sender: Any) {
        NotificationCenter.default.post(name: .someName, object: nil, userInfo: ["someKey": 10])
    }

}

extension Notification.Name {
    static let someName = Notification.Name("someName")
}

解説

まず、Notificationの名前を定義しておきます。

extension Notification.Name {
    static let someName = Notification.Name("someName")
}

次に、NotificationCenterに先ほど定義したNotificationのNameを持つObserverを追加します。
ここで登録したセレクター関数は任意のタイミングでpostした時に呼ばれる関数になります。

override func viewDidLoad() {
    NotificationCenter.default.addObserver(self, selector: #selector(someFunc), name: .someName, object: nil)
}

任意のタイミングでpostして先ほど登録しておいたObserverに処理をするよう通知を発行します。この時、引数のuserInfoに辞書で渡したい値を設定します。

@IBAction private func buttonDidTapped(_ sender: Any) {
    NotificationCenter.default.post(name: .someName, object: nil, userInfo: ["someKey": 10])
}

セレクター関数を定義します。ここで先ほどpostした時に設定した値をNotificationを通して受け取ります。

@objc private func someFunc(notification: Notification) {
    if let num = notification.userInfo?["someKey"] as? Int {
        label.text = String(num)
    }    
}

おわりに

おわりです。

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