xcode 使用 #selector 而不是显式构造 Selector
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36203746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use #selector instead of explicitly constructing a Selector
提问by user523234
In the following snippet, what is the reason why Xcode recommend "Use #selector instead of explicitly constructing a Selector"?
在以下代码段中,Xcode 推荐“使用 #selector 而不是显式构造 Selector”的原因是什么?
// addButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.Add,
// target: self, action: #selector(FoldersMaintenanceVC.addButtonPressed))
addButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.Add,
target: self, action: Selector("addButtonPressed"))
self.navigationItem.leftBarButtonItem = addButton
func addButtonPressed()
{
myNslogSys2(self, funcName:#function)
}
回答by Valentin
It recommends that you use the Swift 2.2 new #selectorbecause it is more type-safe since you cannot make a selector reference to a non-existing method whereas with Selector(String), you could reference a non-existing one.
它建议您使用Swift 2.2 新的 #selector,因为它更类型安全,因为您不能对不存在的方法进行选择器引用,而使用 Selector(String),您可以引用不存在的方法。
回答by Chris
Using #selector
is now the correct way in Swift to reference a selector. Use of the struct Selector
and string literals for selectors, such as "mySel:"
have been deprecated.
Using#selector
现在是 Swift 中引用选择器的正确方法。不推荐使用结构体Selector
和字符串文字作为选择器,例如"mySel:"
已弃用。
The new #selector
is now type safe and allows for compiler checking and autocompletion of the selector that you're passing in. This fixes the very common mistake of a spelling mistake in your selector (in the case of string literals)
新#selector
的现在是类型安全的,并允许编译器检查和自动完成您传入的选择器。这修复了选择器中拼写错误的常见错误(在字符串文字的情况下)
回答by Peter K
It happens cause now construction of Selector from string literals deprecated and will be removed in Swift 3.0
它的发生是因为现在不推荐使用字符串文字构造 Selector 并将在 Swift 3.0 中删除
With the introduction of the #selector syntax, we should deprecate the use of string literals to form selectors. Ideally, we could perform the deprecation in Swift 2.2 and remove the syntax entirely from Swift 3.
随着#selector 语法的引入,我们应该弃用字符串文字来形成选择器。理想情况下,我们可以在 Swift 2.2 中执行弃用,并从 Swift 3 中完全删除语法。
You can read more details about this change here https://github.com/apple/swift-evolution/blob/master/proposals/0022-objc-selectors.md
您可以在此处阅读有关此更改的更多详细信息https://github.com/apple/swift-evolution/blob/master/proposals/0022-objc-selectors.md