Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Unrecognized selector sent to instance" in swift

Tags:

swift

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 development. So far, I have got this:

class ViewController: UIViewController, UITextViewDelegate {      var textView: UITextView!      init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {         super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)     }      override func viewDidLoad() {         super.viewDidLoad()          var widthField = self.view.bounds.size.width - 10         var heightField = self.view.bounds.size.height - 69 - 221         var textFieldString: String! = ""         //Set up text field         self.textView = UITextView(frame: CGRectMake(5, 64, widthField, heightField))         self.textView.backgroundColor = UIColor.redColor()         self.view.addSubview(self.textView)         //Set up the New button         var newButtonString: String! = "New Note"         var heightButton = 568 - heightField - 1000         let newButton = UIButton(frame: CGRect(x: 5, y: 5, width: widthField, height: 50)) as UIButton         UIButton.buttonWithType(UIButtonType.System)         newButton.setTitle(newButtonString,forState: UIControlState.Normal)         newButton.backgroundColor = UIColor.redColor()         newButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)         self.view.addSubview(newButton)      }      func buttonAction() {         println("tapped button")     } } 

I am getting the error "Unrecognized selector sent to instance" when I press the button in the iOS simulator. The app opens fine but whenever the button is pressed, it just crashes.

like image 604
elito25 Avatar asked Jun 07 '14 06:06

elito25


People also ask

What is a selector in Xcode?

A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled.


2 Answers

func buttonAction(){... 

should be

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

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

like image 185
iPatel Avatar answered Oct 08 '22 02:10

iPatel


If you have a colon in the selector name (buttonAction:) you have to have the sender as a n argument for the buttonAction function, if you don't have any colon in the name the sender will not be sent.

like image 32
matsmats Avatar answered Oct 08 '22 03:10

matsmats