1

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

没有使用 Objective-C 选择器“同步”声明的方法

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
4

2 回答 2

12

为了解决您的问题,请首先阅读有关 Swift2.2 中选择器的新文档。

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

这样做是因为这个原因:

对选择器名称使用字符串文字非常容易出错:甚至无法检查字符串是否是格式良好的选择器,更不用说它是否引用任何已知方法或预期类的方法。此外,为了执行 Objective-C API 的自动重命名,Swift 名称和 Objective-C 选择器之间的联系并不明显。通过基于方法的 Swift 名称提供显式的“创建选择器”语法,我们消除了开发人员对实际使用的 Objective-C 选择器进行推理的需要。

于 2016-03-25T08:27:23.303 回答
0

我认为您放错了动作功能“同步”。将它保存在您的 TabBarController 中,因为您已使用 TabBarController 的实例作为目标。如下代码将起作用:

tabBarController.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Upload", style: .Plain, target: tabBarController, action: "sync:")

在 TabBarController 中保留以下函数:

func sync(sender: AnyObject){
    //your code here
}

希望它能解决你的问题。:)

于 2016-03-25T03:38:57.590 回答