Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton AddTarget multiple times on same target action only calls once?

Tags:

This is just a quick question, mostly something I've noticed and been rather confused about. I've played with addTarget in the past, and noticed that if you're calling addTarget dynamically, and set the same target/action twice on say, a button - using addTarget method. Even though we "Added" a target and action more then once, regardless of them being the same target and action, the action itself is only called once.

So, my question - does addTarget ignore adding another target to itself if it already exists in it's stack of target/actions?

like image 254
Braydon Batungbacal Avatar asked Jul 19 '14 22:07

Braydon Batungbacal


1 Answers

UIButton is a UIControl object, which follows an event-listener pattern, which is often implemented with a hashmap (NSDictionary in Objective-C) of targets (aka Listeners or Observers). Since a target is added as a key, it is guaranteed not to be added more than once.

The documentation for addTarget:action:forControlEvents: of UIControl describes this behavior as a safety feature:

It is also safe to call this method multiple times with the same values for the target and action parameters. The control maintains a list of its attached targets and actions along [with] the events each supports.

To disable response for a given control event, the discussion states that you must remove the target-action registration, which is analogous to removing a key from a hashmap:

Specifying a value of 0 for the controlEvents parameter does not prevent events from being sent to a previously registered target and action method. To stop the delivery of events, always call the removeTarget:action:forControlEvents: method.

like image 73
Sheamus Avatar answered Sep 29 '22 21:09

Sheamus