选择器 vs 行为(Swift 4)

13

我是Swift的新手。下面有两个代码片段:

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 的 action 参数提供?
在 Swift 中,SelectorAction 之间的确切区别是什么?

比较如何在Swift 4中处理@objc推断弃用与#selector()? - 正如OOPer所说,这两个示例都需要目标方法为@objc - Hamish
1个回答

10
请查看Swift 4的此提案:SE-0160 Limiting @objc inference
根据提案说明,您的第二个代码片段也需要@objc
实际上,搭配 Xcode 9 beta2 的 Swift 4 编译器会为使用 #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

也许您的第二个代码片段使用 Swift 4 有点过时了。您最好记住通过选择器调用的所有方法都需要@objc属性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接