简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM