引用Objective-C方法的Swift #选择器

时间:2023-01-15 18:29:29

As it possible to conclude in swift 2.2 version it will be possible to reference to the Objective-C method via #selector.

在swift 2.2版本中,尽可能通过#selector引用Objective-C方法。

let sel = #selector(UIView.insertSubview(_:at:)) // produces the Selector "insertSubview:atIndex:"

So previously we wear using name of the method like simple string : "doBangBang" and call it Selector("doBangBang") and now we should use it like reference to the method MyClass.doBangBang() and with usage of key word #selector(MyClass.doBangBang())? Does this feature deprecate Selector? And what benefits are from this improvments except of reducing amount of the functions that were perform with wrong name?

因此,以前我们使用方法的名称,比如简单的字符串:“doBangBang”,并调用它Selector(“doBangBang”),现在我们应该像引用方法MyClass.doBangBang()一样使用它,并使用key word # Selector(MyClass.doBangBang())?这个特性不支持选择器吗?除了减少使用错误名称执行的功能之外,这种改进还有什么好处呢?

1 个解决方案

#1


2  

This feature effectively deprecates using Selector("methodName") and also just using "methodName" or "methodName:" for selectors.

这个特性使用选择器(“methodName”)有效地废弃了,并且只使用“methodName”或“methodName:”作为选择器。

The main benefit is that you can't make typos in the method string anymore, as you already state in the question.

主要的好处是,您不能再在方法字符串中输入拼写错误,因为您已经在问题中声明了这一点。

Imagine a method with a selector:

想象一个有选择器的方法:

..., selector: "myMethod:")

What happens when you typo?

当你打错字时会发生什么?

..., selector: "mymethod:")

It crashes.

它崩溃。

With the new system it's type-safe: the compiler can check that the method you're calling actually exists - no more typos, no more calling non-existing functions:

有了新的系统,它就具有了类型安全:编译器可以检查你调用的方法是否存在——不再有拼写错误,不再调用不存在的函数:

..., selector: #selector(myMethod))

because the compiler can check the types. We also get auto-suggestion and auto-completion from Xcode and all the niceties coming with type-safe operations.

因为编译器可以检查类型。我们还从Xcode中获得自动提示和自动完成,以及所有与类型安全操作相关的细节。

#1


2  

This feature effectively deprecates using Selector("methodName") and also just using "methodName" or "methodName:" for selectors.

这个特性使用选择器(“methodName”)有效地废弃了,并且只使用“methodName”或“methodName:”作为选择器。

The main benefit is that you can't make typos in the method string anymore, as you already state in the question.

主要的好处是,您不能再在方法字符串中输入拼写错误,因为您已经在问题中声明了这一点。

Imagine a method with a selector:

想象一个有选择器的方法:

..., selector: "myMethod:")

What happens when you typo?

当你打错字时会发生什么?

..., selector: "mymethod:")

It crashes.

它崩溃。

With the new system it's type-safe: the compiler can check that the method you're calling actually exists - no more typos, no more calling non-existing functions:

有了新的系统,它就具有了类型安全:编译器可以检查你调用的方法是否存在——不再有拼写错误,不再调用不存在的函数:

..., selector: #selector(myMethod))

because the compiler can check the types. We also get auto-suggestion and auto-completion from Xcode and all the niceties coming with type-safe operations.

因为编译器可以检查类型。我们还从Xcode中获得自动提示和自动完成,以及所有与类型安全操作相关的细节。