What's the best way to call an IBAction from with-in the code?

24,408

Solution 1

The proper way is either:

- [self functionToBeCalled:nil] 

To pass a nil sender, indicating that it wasn't called through the usual framework.

OR

- [self functionToBeCalled:self]

To pass yourself as the sender, which is also correct.

Which one to chose depends on what exactly the function does, and what it expects the sender to be.

Solution 2

Semantically speaking, calling an IBAction should be triggered by UI events only (e.g. a button tap). If you need to run the same code from multiple places, then you can extract that code from the IBAction into a dedicated method, and call that method from both places:

- (IBAction)onButtonTap:(id)sender {
    [self doSomething];
}

This allows you to do extra logic based on the sender (perhaps you might assign the same action to multiple buttons and decide what to do based on the sender parameter). And also reduces the amount of code that you need to write in the IBAction (which keeps your controller implementation clean).

Share:
24,408
iwasrobbed
Author by

iwasrobbed

I work mostly with Swift/Objective-C and I open source a lot, including a video social network built with Ruby on Rails. I also dabble in Photoshop / Sketch. I am a Mechanical Engineer by training. Swift cheat sheet: https://github.com/iwasrobbed/Swift-CheatSheet ObjC cheat sheet: https://github.com/iwasrobbed/Objective-C-CheatSheet

Updated on July 18, 2020

Comments

  • iwasrobbed
    iwasrobbed almost 4 years

    Say for instance I have an IBAction that is hooked up to a UIButton in interface builder.

    - (IBAction)functionToBeCalled:(id)sender
    {
       // do something here   
    
    }
    

    With-in my code, say for instance in another method, what is the best way to call that IBAction?

    If I try to call it like this, I receive an error:

    [self functionToBeCalled:];
    

    But, if I try to call it like this (cheating a bit, I think), it works fine:

    [self functionToBeCalled:0];
    

    What is the proper way to call it properly?