“Unrecognized selector sent to instance” in swift

后端 未结 10 467
刺人心
刺人心 2020-12-10 10:36

I have no idea what I am doing wrong. I am also quite new to programming so I am not very good at debugging. This was a test app so that I can see how swift ties in with app

相关标签:
10条回答
  • 2020-12-10 11:24

    For those who end up in my shoes: If you're creating your button in a static context, ensure you're passing the correct target to UIButton.addTarget(_:action:for:). Passing self will result in passing the type not an instance.

    0 讨论(0)
  • 2020-12-10 11:27

    I know this is too late to answer this question but I'm answering this for anyone who stumbles into a similar type of issue. Recently I had an "Unrecognised selector sent to instance" issue which took me a whole day to debug. So I'm listing possible causes for the issue hope this helps someone facing this error.

    Usually, this error is thrown when you pass a selector to an instance but that selector isn't there. In simple words, it's like someone gives a courier guy an address to deliver but that address is inexistent.

    How to debug: 1. First, check all of your @objc marked methods: when you call an @objc marked method using #selector() syntax the method signature should be exactly the same.

    1. This type of error can also arise when you are making an invalid casting of the object. This was my case. I was setting an attributed string to a label and in the attributes passed an enum case (TextProperty.title) instead of (TextProperty.title.font). so the font variable returns a UIFont object.

    since the keys in the attribute, dictionary expect "Any" Xcode didn't throw an error. So the font attribute was expecting a UIFont but got TextProperty enum case instead. So do check if you are doing an invalid cast in your code.

    1. There can be a memory leak in your code. eg: you could be sending a selector to an instance but that selector is wiped out of memory.

    These are the cases that I could think of. If you have something that can help you are welcome for suggestions.

    0 讨论(0)
  • 2020-12-10 11:30
    func buttonAction(){...
    

    should be

    func buttonAction(sender:UIButton!)
    {
        println("tapped button")
    }
    

    Because of newButton's action: "buttonAction:" so.

    0 讨论(0)
  • 2020-12-10 11:30

    Adding an @IBAction function to your code and then deleting or renaming it without updating your storyboard will also cause this error.

    Look at the selector in the error message:

    '-[HelloWorld.ViewController yourActionFunction:]: unrecognized selector sent to instance 0x157e0c830'
                                 ^^^^^^^^^^^^^^^^^^
    

    Do you have a function named yourActionFunction? If not, select the storyboard and edit the connections on your control (e.g. button).

    0 讨论(0)
提交回复
热议问题