一応他のバージョンのサンプルも載せておく
Swift3でSelectorのサンプルコード
#selector(クラス名.関数名の形式)
self.は省略可能
func sample() {
let nc = NotificationCenter.default
nc.addObserver(
self,
selector: #selector(self.selectorTest),
// selector: #selector(CustomViewController.selectorTest), // こっちでもOK
name: Notification.Name(rawValue:"test"),
object: nil)
}
func selectorTest(notification: Notification?) {
print("notification")
}
Swift2.2 以降 Selectorサンプルコード
確かこのバージョンからセレクタが存在するかチェックしてくれるようになったはず
#selector(クラス名.関数名の形式(_:))
func sample() {
let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(
self,
selector: #selector(CustomViewController.selectorTest(_:)),
name: "test",
object: nil)
}
Swift2.1 以前 Selectorサンプルコード
方針が固まっていなかったのかだいぶ辛いことになってた
Selector("関数名:")
func sample() {
let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(
self,
selector: Selector("selectorTest:"),
name: "test",
object: nil)
}
Objective-C Selectorサンプルコード
Objective-C はまだ使う機会があるかもしれない
- (void) sample() {
NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(selectorTest:) name:@"test" object:nil];
}
参考
http://dev.classmethod.jp/smartphone/swift-3-0-notificationcenter/
以前は文字列でセレクタ(メソッド名)を指定するという辛い仕様だったけど、負の遺産感は払拭できた感じ?