Xcode 7.3 / Swift 2:"No method declared with Objective-C selector" 警告

Xcode 7.3 / Swift 2: "No method declared with Objective-C selector" warning

我使用选择器有一段时间了,甚至在迁移到 Swift 之后我也能够毫无问题地使用它们。这就是我在 Swift 2 上使用的方式,直到我将 Xcode 更新到 7.3 版:

如用户所见,我将选择器与 NSTimer 一起使用。

这是调用的操作:

 func Start () {

 }

如您所见Xcode 7.3 现在给出警告"No method declared with Objective-C selector"。通过单击警告,Xcode 通过添加 "Selector" 提供了对代码的快速修复,但我仍然收到相同的警告:

从 Swift 2.2 / Xcode 7.3 开始,有一种使用 selector 的新方法: Selector("funcName") 已更改为 #selector(ClassName.funcName)

看看 https://github.com/apple/swift-evolution/blob/master/proposals/0022-objc-selectors.md ,

tl;博士;

Selector("Start")替换为#selector(YOUR_CLASS.Start)

其中 YOUR_CLASS = class 给定上下文中的目标。

如果您不想手动修复,Xcode 默认提供简单的修复,当您遇到以下情况时,点击黄色三角形(有时需要 tap/click 多个次 ),

它会给你建议:

如果您 select 该建议,它会自动更新 select 或者:

以下两个语句都可以完美运行。上面那个用的最多。 However when the selector method is in a different ViewController the compiler warning "No method declared with Objective-C selector 'buttonHandler'" may occur.

第二个列出的语句没有给出此警告。

button.addTarget(parentViewController, action: Selector("buttonHandler:"), forControlEvents: .TouchUpInside)

button.addTarget(parentViewController, action: #selector(MainViewController.buttonHandler), forControlEvents: .TouchUpInside)

在目标视图控制器(MainViewController)中你可以定义模块:

func buttonHandler(sender:UIButton!) {
    print ("Pressed")
}

我自己的一些发现来支持文森特所说的(太长而不能直接评论)

它不一定在不同的视图控制器中,而只是在以下格式不起作用的不同文件中:

button.addTarget(parentViewController, action: Selector("buttonHandler:"), forControlEvents: .TouchUpInside)

例如,如果您在单独的文件中有扩展名,尽管对于同一个视图控制器,这种格式 Selector("buttonHandler:") 将不起作用。

Further, when the selector is in the same file and VC, Xcode's quick-fix prompts you to have the selector include the构造函数,所以它看起来像这样:

#selector(MainViewController.buttonHandler(_:))

但是此格式仅在选择器在相同VC +文件中,如果它在单独的文件中,但是VC ,那么那个推荐的方法就不行了,你需要使用没有构造函数的方法

#selector(MainViewController.buttonHandler)

在 Swift 4 上,我不得不在 func 之前添加 @objc 以消除警告。

这是我用 NSTimer 调用函数的方式:

 Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.intro), userInfo: nil, repeats: false)

函数是这样声明的:

     @objc func intro () {

          // do your stuff here         

     }

我还按照 Xcode 的要求更新了设置:

没有更多警告,似乎一切正常。