Search code examples
xcodecocoastoryboardibaction

Why is @IBAction automatically called on launch?


If you create a new Cocoa project and drag and drop NSTextField from Object Library to your view controller, which is your initial controller upon launch, and create both a @IBAction (add print(called) in it) and @IBOutlet, and run the app, then you don't see the @IBAction method called upon launch.

Then, if you push a return on the text field, you get the action called. However, and this is important, that after you quit the app and then launch the app again, you come to see now that the @IBAction is called upon launch for some reasons (If you don't, try it a couple of times).

In actuality I wondered why @IBAction was always called upon launch in my development app, and searched for any methods calling it in all of my classes, but later found that this strange problem happens even when I start a new project and create a connection, and try launching and sending the action a few times of trial and error.

I also note that I created five new projects and confirmed that this happened in all of the five projects.

Why does this occur? Also, if this is the bug on Apple's side, is there any way to disable the automatic execution of the @IBAction in my project?

I set textField.editable = false at first and set it to textField.editable = true in viewDidAppear:, but still triggered the action upon launch. Is there any way to cope with the issue?


It seems that if I close the window by tapping on the red icon and quitting the app, and then launching it again from within Xcode, then the @IBAction is not called. This is so strange...


Solution

  • This seems to be connected to window restoration on OS X.

    Your text field is set as the first responder when the view loads. Then, during restoration, the window becomes the first responder. That causes the text field to resign first responder, which fires an action.

    In IB, you can set the action of your text field to be "Send on enter only". (By default it's "end editing".)

    Or, you can make your window non-restorable if you prefer that.