2017-06-30 60 views
12

新斯威夫特。我有空兩個片段:選擇VS斯威夫特行動4

NotificationCenter.default.addObserver(self, 
    selector:#selector(ViewController.notificationReceived), 
    name: Notification.Name(rawValue: name), object: nil) 

@objc func notificationReceived(notification:Notification){ 
    let x = notification.userInfo! 
    print("\(x["name"]!)") 

} 

最後

let x:UITapGestureRecognizer = UITapGestureRecognizer(target: self, 
    action: #selector(tapped)) 

self.addGestureRecognizer(x) 

func tapped(){ 
    print("tapped") 

    self.delegate!.theViewTapped() 

} 

爲什麼是它的notificationCenter?我應該提供的selector參數@objc標籤,但不是爲UITapGestureRecognizer動作參數?

究竟是SelectorAction in斯威夫特之間的區別?

+0

比較[在Swift 4中,我如何處理@o​​bjc推斷棄用#selector()?](https://stackoverflow.com/q/44390378/2976878) - 正如OOPer所說,這兩個示例都需要目標方法是'@ objc'。 – Hamish

回答

9

檢查這個提議雨燕4: SE-0160 Limiting @objc inference

根據該提案的說明,你的第二個代碼片段也需要@objc

事實上,斯威夫特4編譯器和Xcode 9β2捆綁器使用#selector(tapped)此錯誤行:

error: argument of '#selector' refers to instance method 'tapped()' that is not exposed to Objective-C

note: add '@objc' to expose this instance method to Objective-C

也許你的第二個是有點太舊有斯威夫特4.使用你最好想通過選擇調用的所有方法需要@objc屬性。