Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

nstimer

I've been using selectors for a while, and even after migrating to Swift I was able to use them without issues. That's how I was using on Swift 2 without issues until I updated Xcode to version 7.3:

enter image description here

As use can see I use selectors with NSTimer.

This is the action that is called:

 func Start () {

 }

As you can see Xcode 7.3 now gives a warning "No method declared with Objective-C selector". By clicking on the warning, Xcode offers a quick fix to the code by adding "Selector", but then I still get the same warning:enter image description here

like image 558
tomDev Avatar asked Mar 22 '16 16:03

tomDev


Video Answer


3 Answers

Since Swift 2.2 / Xcode 7.3 there is a new way to use a selector: Selector("funcName") was changed to #selector(ClassName.funcName)

Have a look at https://github.com/apple/swift-evolution/blob/master/proposals/0022-objc-selectors.md ,

tl;dr;

Replace Selector("Start") with #selector(YOUR_CLASS.Start)

where YOUR_CLASS = class of target in given context.

If you don't want to do it manually, Xcode provides easy fix itself by default, when you have the following situation, tap on the Yellow triangles ( sometimes required to tap/click multiple times ),

enter image description here

it will give you suggestion: enter image description here

And if you select that suggestion, it will automatically update the selector: enter image description here

like image 84
ogres Avatar answered Oct 16 '22 23:10

ogres


Both following statements work perfectly. The upper one is mostly used. However when the selector method is in a different ViewController the compiler warning "No method declared with Objective-C selector 'buttonHandler'" may occur.

The second listed statement does not give this warning.

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

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

In the target view controller (MainViewController) you can define the module:

func buttonHandler(sender:UIButton!) {
    print ("Pressed")
}
like image 4
Vincent Avatar answered Oct 16 '22 23:10

Vincent


On Swift 4 I had to add @objc before the func to get rid of the warnings.

This is how I call the func with NSTimer:

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

This is how the func is declared:

     @objc func intro () {

          // do your stuff here         

     }

I also updated the setting as the Xcode requested:

enter image description here

No more warnings, everything seems to be working fine.

like image 2
tomDev Avatar answered Oct 16 '22 23:10

tomDev