Implement Target-Action Design Pattern in Objective-C

I am trying to implement a Target-Action design pattern in a custom class. The interface will have the following method:

- (void)addTarget:(id)target action:(SEL)action forEvents:(MyEvents)events; 

MyEvents is an NSUInteger. What is the best way to store this information in my class? Opening the UIControl.h file, I noticed that UIKit contains the following:

 NSMutableArray* _targetActions; 

I believe that all actions are added to this array encapsulated in NSObject (do I need to create another custom object or is there something I can reuse?), And every time it needs to perform an action, it iterates through the array, using bitmasks as a filter. Is it correct?

Thanks in advance.

+6
source share
1 answer

This array contains instances of a private class called UIControlTargetAction . This is just a POD class with three instance variables:

 id _target; SEL _action; int _eventMask; 

You can easily create your own version. Then, when you have an event, you just do something like:

 for (MyTargetAction *targetAction in targetActions) { if (targetAction.eventMask & myEventMask) { [targetAction.target performSelector:targetAction.action]; } } 
+6
source

Source: https://habr.com/ru/post/887742/


All Articles