LoginSignup
106
104

More than 5 years have passed since last update.

SwiftでNSNotificationCenterを使う

Last updated at Posted at 2014-07-18

登録時のselectorの指定方法で迷ったのでメモ。

登録

NSNotificationCenter.defaultCenter().addObserver(self, selector: "update:", name: MyNotification, object: nil)

削除

NSNotificationCenter.defaultCenter().removeObserver(self)

通知を受けた時に実行するメソッド

func update(notification: NSNotification?) {
    // 何かする
}

通知

NSNotificationCenter.defaultCenter().postNotificationName(MyNotification, object: nil)

通知名の定義

let MyNotification = "MyNotification"

その他、注意点(追記:15/03/30)

NSObjectを継承していないクラスで使用する場合は
実行するメソッドに@objcを指定する必要があるようです。

通知を受けた時に実行するメソッド(NSObject非継承時)

@objc
func update(notification: NSNotification?) {
    // 何かする
}

サンプル

NSObjectを継承している場合

import UIKit

let MyNotification = "MyNotification"

class Hoge : NSObject {
    override init() {
        super.init()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "update:", name: MyNotification, object: nil)
    }

    func update(notification: NSNotification?) {
        // 何かする
        print("Notification!")
    }
}

var hoge = Hoge()

// 通知してみる
NSNotificationCenter.defaultCenter().postNotificationName(MyNotification, object: nil)

NSObjectを継承していない場合

import UIKit

let MyNotification = "MyNotification"

class Hoge {
    init() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "update:", name: MyNotification, object: nil)
    }

    @objc
    func update(notification: NSNotification?) {
        // 何かする
        print("Notification!")
    }
}

var hoge = Hoge()

// 通知してみる
NSNotificationCenter.defaultCenter().postNotificationName(MyNotification, object: nil)
106
104
3

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
106
104