Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the Target-Action Design Pattern in Objective-C

I'm trying to implement the 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 a NSUInteger. What's the best way to store these informations on my class? Opening the file UIControl.h I noticed that UIKit contains the following:

NSMutableArray* _targetActions;

I suppose that all actions are added in this array encapsulated in an 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 the array using the bitmask as a filter. Is it correct?

Thanks in advance.

like image 585
emix Avatar asked May 10 '11 16:05

emix


1 Answers

That array holds instances of a private class called UIControlTargetAction. It's just a POD class that has three instance variables:

id _target;
SEL _action;
int _eventMask;

You could create your own version quite easily. 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];
    }
}
like image 109
Chuck Avatar answered Oct 16 '22 22:10

Chuck