swift - 引用方法的 Objective-C 选择器

标签 swift swift2

<分区>

从 Swift 2.2 开始,以下代码会发出警告:

No method declared with Objective-C selector'sync'

if let tabBarController = segue.destinationViewController as? TabBarController {
  tabBarController.navigationItem.rightBarButtonItem = 
    UIBarButtonItem(title: "Upload", 
                    style: .Plain, 
                    target: tabBarController, 
                    action: "sync")

我应该用什么替换 action: "sync" 来消除警告?

我试过:

Selector("sync") // The Xcode provided fix which yields the same warning
#selector(tabBarController.sync()) // Error: Argument of '#selector' does not refer to initializer or method 
Selector(tabBarController.sync()) // No error/warning but doesn't fire sync function

最佳答案

要解决您的问题,请首先阅读新的 documentation关于 Swift2.2 中的选择器。

例子: 使用 #selector(CLASS.sync) 而不是 Selector("sync")。其中 CLASS 是包含此方法的实际类。

这是由于这个原因而完成的:

The use of string literals for selector names is extremely error-prone: there is no checking that the string is even a well-formed selector, much less that it refers to any known method, or a method of the intended class. Moreover, with the effort to perform automatic renaming of Objective-C APIs, the link between Swift name and Objective-C selector is non-obvious. By providing explicit "create a selector" syntax based on the Swift name of a method, we eliminate the need for developers to reason about the actual Objective-C selectors being used.

关于swift - 引用方法的 Objective-C 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36213467/

相关文章:

ios - 重命名uitableview部分的标题

swift - 将堆栈 View 的大小固定为所有屏幕尺寸

ios - Swift:从另一个 viewcontroller 调用 ViewController func

ios - 使 UIView 接收点击但将滑动传递给基础 View

ios - Swift函数不接受变量

swift2 - Swift 以清晰的方式实现选择器

ios - 在导航 Controller 中返回到 View Controller 时,整个屏幕都是空白的

ios - 如何为注释创建一个数组

swift - 在 Swift 的 case 语句中赋值的 2 种方式

arrays - Swift 2 NSUserDefaults 读取数组