为什么使用选择器需要@objc标记? [英] Why is the @objc tag needed to use a selector?
问题描述
我正在尝试使用选择器来查看某个协议是否可以执行操作.当我这样尝试时:
I am trying to use a selector to see if a certain protocol can perform an action. When I try it like this:
protocol Test {
func hello()
func goodBye(a: String)
}
class Tester: NSObject, Test {
override init() {}
func hello() { }
func goodBye(a: String) { }
}
let a: Test = Tester()
let result = a.responds(to: Selector("goodByeWithA:"))
在这种情况下,result
的计算结果为false
.
In this case, result
evaluates to false
.
但是,如果我将@objc
标签添加到协议中,则其评估结果为true
.
But if I add the @objc
tag to the protocol, it evaluates as true
.
@objc protocol Test {
func hello()
func goodBye(a: String)
}
这是为什么?
另一方面,我知道现在建议使用#selector
语法并远离使用字符串,但是出于各种原因,在这种情况下,我必须使用字符串.
On a side note, I know that it is now recommended to use the #selector
syntax and to move away from using strings, but for various reasons, I have to use a string in this case.
只有当我将项目迁移到Swift 4.2后,这种情况才开始发生
This only started happening once I migrated my project to Swift 4.2
推荐答案
默认情况下,Swift生成仅对其他Swift代码可用的代码,但是如果您需要与Objective-C运行时进行交互–例如所有UIKit –您需要告诉Swift该怎么做.
By default Swift generates code that is only available to other Swift code, but if you need to interact with the Objective-C runtime – all of UIKit, for example – you need to tell Swift what to do.
这就是@objc属性的来源:将其应用于类或方法时,它会指示Swift将这些内容提供给Objective-C和Swift代码.因此,每次您要从UIBarButtonItem或Timer调用方法时,都需要使用@objc标记该方法,以便将其公开-这两个以及许多其他都是Objective-C代码.
That’s where the @objc attribute comes in: when you apply it to a class or method it instructs Swift to make those things available to Objective-C as well as Swift code. So, any time you want to call a method from a UIBarButtonItem or a Timer, you’ll need to mark that method using @objc so it’s exposed – both of those, and many others, are Objective-C code.
不用担心:如果您忘记了在需要时添加@objc,则代码根本就不会编译-这不是您会偶然忘记并引入错误的东西.
Don’t worry: if you forget to add @objc when it’s needed, your code simply won’t compile – it’s not something you can forget by accident and introduce a bug.
这篇关于为什么使用选择器需要@objc标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!