4

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.
}
Shamas S
  • 7,507
  • 10
  • 46
  • 58
  • Very similar Q&A here: http://stackoverflow.com/questions/24415662/object-x-of-class-y-does-not-implement-methodsignatureforselector-in-swift. – Martin R Apr 02 '15 at 09:18

2 Answers2

12

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.

Shamas S
  • 7,507
  • 10
  • 46
  • 58
3

Another option is to add @objc to your class declaration.

I have found that using NSTimer invocations crash otherwise.

Rivera
  • 10,792
  • 3
  • 58
  • 102