0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】ファイル間のイベント通知に便利!NotificationCenter

Last updated at Posted at 2023-08-22

目次

1.NotificatonCenterとは
2.メリット
3.使い方
4.おわりに

1. NotificationCenterとは

  • 一言で言うと「ファイル間でイベントを検知する仕組みのこと」です。
  • 登場人物は「Borker(仲介人)」、「Publish(出版)」、「Subscribe(購読)」の3人です。
  • 図にすると以下のような感じになりますNotification.png

2. メリット

  • 異なるオブジェクト間(ファイル間)でイベントが起こった際に別のオブジェクトへ通知する仕組みが簡単に実装できます。
  • 監視したいイベントがあるファイルにpost、イベントの検知により処理をしたいファイルにaddObserverするだけで実装できます。

3. 使い方

配置方法

  • Publish:イベントを検知したいファイル処理に配置

  • Broker : NotificationCenterクラス自身のこと

  • Subscribe : イベント検知により処理を行いたい部分へ配置

  • 具体例

    • イベントを送信したいファイル
    sendViewController.swift
    let UIBtn = UIButton()
    UIBtn.addTarget(self, action: #selector(onClickBtn), for: .touchUpInside)
    
    @objc func onClickBtn() {
        print("UIButton Pushed")
        // 通知を送りたい箇所でこのように記述
        NotificationCenter.default.post(name: "UIButtonPushed", object: nil)
    }
    
    • イベントを受け取りたいファイル
    recievedViewContoroller.swift
    override func viewDidLoad() {
        super.viewDidLoad()
        // NotificationCenterを登録
        NotificationCenter.default
            .addObserver(self, selector: #selector(recievedKnowtice()), name: "UIButtonPushed", object: nil)
    }
    
    @objc func recievedKnowtice() {
        print("recieved Pushed Knowtice")
    }
    

4. おわりに

本記事ではNotificationCenterについて解説いたしました。
イベントを送信したい部分と、受け取りたい部分にそれぞれpost, addObserverを記述するだけで簡単にオブジェクト間のデータの受け渡しが出来るとは画期的ではないですか?
他言語経験者の私からすると相当、画期的に思いました笑

目指せ脱初学者!
最後までご覧いただきありがとうございました♪

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?