0
1

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 3 years have passed since last update.

Notificationを使ったオブザーバパターンを理解

Posted at

Notification

PosterObserverは直接繋がっていないが、addObserverを使って、通知を監視し通知があった際に#selecterで指定した関数を実行可能です。

import Foundation

class Poster {
    static let notificationName = Notification.Name("SomeNotification")
    
    func post(message: String) {
        NotificationCenter.default.post(name: Poster.notificationName, object: message)
    }
}

class Observer {
    init() {
        NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: Poster.notificationName, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func handleNotification(_ notification: Notification) {
        if let object = notification.object {
            print(object)
        }
        print("通知を受け取りました")
    }
}

var observer = Observer()
let poster = Poster()
poster.post(message: "Hello")


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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?