Using an IBAction method when it is not called from an action?
-
26-09-2019 - |
Question
Are there any issues when using IBAction when it is not actually called from a user's action?
If you have an action like
-(IBAction)sayHello:(id)sender;
You can call it from within your class like:
[self sayHello:@"x"]
The @"x" doesn't do anything, it just fills in for the sender.
You can actually create an IBAction method without (id)sender
-(IBAction)sayHello;
and call it from both user's actions and from within the code, but then you won't get any useful sender info from the interface. What's the 'correct' way of filling in for the sender, when calling from the code? And can you create sender info to send when it's called from within the code?
Just trying to figure it out.
Solution
I think a good practice for OOP is to refractor the method -(IBAction)sayHello:(id)sender;
to another method called: -(void)sayHello; and inside the method -(IBAction)sayHello:(id)sender { [self sayHello]; }
If other methods want to call the sayHello:(id)sender action to do some job, it can call the sayHello. The method name should make sense for the client to call it without a problem or work around. It will help you when you have to test or debug
OTHER TIPS
The sender should be a UI component. So if in your class you have, say, a UIButton...
UIButton *button;
Then you can just send it as parameter to the action:
[self sayHello:button];
Insider the method, no matter if it is called from the UI or in some simulated way, you can have some logic to detect who the sender is, and behave differently based on that. This way, multiple buttons or other components can reuse the same action method.
Unless you're actually making use of the sender
parameter (see Jaanus's answer for more on that), you're fine with passing nil
for it when calling the method from code.