【Xcode(Swift)】「NotificationCenter」解説

Xcode(Swift/Objective-C)における、技術メモです。
自身の脳内整理・備忘録を兼ねてメモしています。
今回は「NotificationCenter」についてです。

※もし内容に誤りなどございましたら、下部「コメント」欄にいただけるとありがたいです。

概念

「NotificationCenter」とは、登録されたオブザーバーへブロードキャストで連携できる通知メカニズムです。

「②必要な部位で発生させる(post)」は、キーボードが画面に表示された時(UIResponder.keyboardWillShowNotification)のように、イベント発生をトリガに「③処理A」を実行するような使い方ができます。

(むしろ、そういったケースに使うことが多い?)

 

仕様

ドキュメンテーション、関連ページ

Apple Developer Documentation

A notification dispatch mechanism that enables the broadcast…

Qiita

今回、あるViewControllerから別のViewControllerに処理を伝搬したいものがあり、調べたところ、N…

確認バージョン

Xcode:11.3.1
Swift:5.1.3

Swift 3にて、NotificationCenterが改良されています。(旧:NSNotificationCenter)」

使い方

【Swift】(3.0以降)

// NotificationCenterのインスタンスを作成
let nc = NotificationCenter.default


// NotificationCenterに定義を登録
// 下記例は
/ /Notification名は「TestNotification」
// 通知された時(送信された時)に起動する処理は「ncAction」
nc.addObserver(self, selector: #selector(self.ncAction), name: Notification.Name(rawValue:"TestNotification"), object: nil)
// デフォルトで定義済のイベントをnameに登録することも可能(例:UIResponder.keyboardWillShowNotification)
nc.addObserver(self, selector: #selector(self.ncAction), name: UIResponder.keyboardWillShowNotification, object: nil)

// NotificationCenterに送信
// 上記で登録した「TestNotification」を発生させている
nc.post(name: Notification.Name(rawValue:"TestNotification"), object: nil)


// Notificationを受信した時に処理する関数
func ncAction(notification: Notification?){
    print("通知を受信しました!")
}

// NotificationCenterに登録した定義を解除
// iOS9.0 or macOS 10.11以降の場合は解除は不要のようです。
// 全て解除
nc.removeObserver(self)
// 個別に解除
nc.removeObserver(self, name: Notification.Name(rawValue:"TestNotification"), object: nil)
Apple Developer Documentation

Removes matching entries from the notification center's disp…

※ご回答希望の場合は、ご連絡先も記入ください
"意見が持てる" デジタルコラム
絶賛配信中!

メルマガ詳細はこちら >>>

送信時点で「Privacy Policy」に同意したものとみなします。
広告を含むご案内のメールをお送りする場合があります。
   
         
最後までお読みいただき、ありがとうございました。
以下も、ぜひご活用ください^^
出版物
ITmedia
メルマガ
Site Access Log by HTTP Header

    >情報システムの

    情報システムの"教科書"本を発売中!


    ■ 情シス、システムコンサルタント、システムエンジニアの方へ
    情シスの定石(技術評論社)

    ■ システムエンジニア、情シスの方へ
    2023年10月7日(土)発売
    システム設計の教科書(技術評論社)

    CTR IMG

    ■ 著者 石黒直樹による書籍説明動画