Shamas S Shamas S - 7 months ago 100
Swift Question

UIButton click crashing does not implement methodSignatureForSelector: -- trouble ahead Unrecognized selector

In Swift when the button is pressed the App crashes with error


does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector


In the code a Controller class of mine gets a reference to a UIButton and adds a target like the following

aButton.addTarget(self, action: "pressed:", forControlEvents: UIControlEvents.TouchUpInside)


The function pressed is defined as

func pressed(sender:UIButton)
{
println("button pressed")
}


Controller class is defined like

class MyController
{
init()
{
}
// Also here it gets the reference to the UIButton and has pressed function as well.
}

Answer

The problem as I discovered was that MyController class need to inherit from NSObject class. Changing the class declaration to as following fixed my problem.

class MyController : NSObject
{
    override init() // since it is overriding the NSObject init
    {
    }
}

This is probably because NSObject implements methods like respondsToSelector. And before calling the pressed: function it tries to check if it infact implements the selector pressed:. But since MyController doesn't have respondsToSelector either, so it crashes.