Help us understand the problem. What is going on with this article?

SwiftでNSNotificationCenterを使う

More than 3 years have passed since last update.

登録時の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)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away