NotificationCenterを使ってみました

はじめに

iOSアプリで、ある画面で処理したタイミングで別画面の表示を更新したいことがあります。 このような場合には、Observerデザインパターンが有効です。 Observerパターンは、Listenerパターンとも呼ばれます。

Java言語の場合にはListenerをインタフェースとして実装することが多いです。

swiftでは、Observerデザインパターン用のクラスとしてNotificationCenterが提供されています。

ソースコードは、githubにあります。

実装

  • 登録
  • 登録解除
  • 通知を送信
// Notification名を登録する
public extension Notification {
    public static let MyNotificationName = Notification.Name("Notification.MyNotification")
    public static let MyNotificationNameUserInfo = Notification.Name("Notification.MyNotificationUserInfo”)
}
class Hoge : NSObject {
    override init() {
        super.init()
    // 登録
        NotificationCenter.default.addObserver(self, selector: #selector(self.update), name: Notification.MyNotificationName, object: nil);

    // 通知を受けるメソッドです
    func update(notification: NSNotification) {
        print("receive Notification!")
    }

    // 登録解除
    func removeObserver() {
        NotificationCenter.default.removeObserver(self, name: Notification.MyNotificationName, object: nil)
    }
}
var hoge = Hoge()

// 通知する
NotificationCenter.default.post(name: Notification.MyNotificationName object: nil)

通知するタイミングでデータを受け渡したい場合には、UserInfoが使えます。

class HogeUserInfo : NSObject {
    override init() {
        super.init()
        // 受信側(登録)
        NotificationCenter.default.addObserver(self, selector: #selector(self.update), name: MyNotificationNameUserInfo, object: nil)
    }
    
    // 通知を受けるメソッドです
    func update(notification: NSNotification) {
        print("receive Notification!")
        
        guard let userInfo = notification.userInfo,
            let message  = userInfo["message"] as? String,
            let date     = userInfo["date"]    as? Date else {
                print("No userInfo found in notification")
                return
        }
        print(message);
        print(date);
    }
}

var hogeUserInfo = HogeUserInfo()

// 通知する
NotificationCenter.default.post(name: Notification. MyNotificationNameUserInfo, object: nil, userInfo:["message":"Hello there!", "date":Date()])

リンク