Swift3でSelector(NotificationCenter)

~Swift2.1, 2.2と若干迷走気味だったけどSwift3でシンプルに記述できるようになった模様
一応他のバージョンのサンプルも載せておく




Swift3でSelectorのサンプルコード



#selector(クラス名.関数名の形式)
self.は省略可能

1
2
3
4
5
6
7
8
9
10
11
12
13
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(クラス名.関数名の形式(_:))

1
2
3
4
5
6
7
8
func sample() {
    let nc = NSNotificationCenter.defaultCenter()
    nc.addObserver(
        self,
        selector: #selector(CustomViewController.selectorTest(_:)),
        name: "test",
        object: nil)
}      



Swift2.1 以前 Selectorサンプルコード


方針が固まっていなかったのかだいぶ辛いことになってた
Selector("関数名:")

1
2
3
4
5
6
7
8
func sample() {
    let nc = NSNotificationCenter.defaultCenter()
    nc.addObserver(
        self,
        selector: Selector("selectorTest:"),
        name: "test",
        object: nil)
}      




Objective-C Selectorサンプルコード


Objective-C はまだ使う機会があるかもしれない

1
2
3
4
- (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/


以前は文字列でセレクタ(メソッド名)を指定するという辛い仕様だったけど、負の遺産感は払拭できた感じ?

2016年12月6日火曜日