Jim
Jim

Reputation: 9234

iPhone: IBAction vs Selector

I have a Button1 which has IBAction. Also I set target and action for my button

- (void)setTarget:(id)target action:(SEL)action {
  [self.Button1 addTarget:target action:action 
       forControlEvents:UIControlEventTouchUpInside];
}

So when I pressed the button firstly IBAction did what he should, and than action that I set to button. Is that order always be like that ?

Upvotes: 1

Views: 509

Answers (1)

Jamie Stewart
Jamie Stewart

Reputation: 331

If you are loading you view or view controller from a nib file then yes the pattern will always be the IBAction even first followed by the target you have added to the button.

In effect adding an IBAction in Interface Builder is really just telling IB to call ["UIControl" addTarget:"id" forControlEvents:"UIControlEvent"], and you can add multiple targets to a UIButton.

In effect your code will load everything from the NIB file first (if you are using initWithNib:named:), so this will call the addTarget function on the button first with the action you have specified in Interface Builder, then at some later point the setTarget function you have above will get called, which will add another target action to the button. A UIControls targets are stored in an array which is accessed in order and will trigger if control events are met in the order they were created in. If you look in the header file for UIControl (the super class for UIButton) you will see that NSMutableArray* _targetActions is an array. So the order is guaranteed to fire like this unless you reorder this array after it is created at some point.

Upvotes: 3

Related Questions