Implement target action template without subclass of UIControl

I am developing a college timer application. My main timer class is a subclass of NSObject. I want other objects to be logged for timer events such as timer, pause, timer over, etc. I think that the target action pattern will be most suitable for this, but how would I implement this? I need to be able to add multiple goals for each specific action, just like UIButton does.

Any help is appreciated.

+4
source share
3 answers

Here is an easy way to add some goals. Obviously, you want to create some error checking and make it more flexible, but hopefully you get the idea:

Write a method that allows other objects to add themselves as a target:

- (void) addTarget:(NSObject *)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents { if (controlEvents == UIControlEventValueChanged) { NSArray *targetAndAction = @[target, [NSValue valueWithPointer:action]]; [valueChangedArray addObject:targetAndAction]; // valueChangedArray is a NSMutableArray, already initialized } } 

You do not need to use UIControlEvents if you do not want this, and you do not need to use NSArrays to store all the material. The important thing is that you hover over the target and save the selector as an NSValue object.

When something happens, do an object selector:

 - (void) somethingHappened { // something happened, inform the objects who registered for (NSArray *targetAndAction in valueChangedArray) { NSObject *target = targetAndAction[0]; NSValue *actionValue = targetAndAction[1]; SEL action = [actionValue pointerValue]; [target performSelector:action]; } } 

Note that you may get a memory leak if the selector saves any objects (Xcode will warn you about this). Until your selectors return the objects they created / copied, you should be fine. A more detailed discussion of potential leakage potential leakage is available here: performSelector may cause leakage because its selector is unknown .

+5
source

A notification template is best for your application. You must use NSNotificationCenter for this .

Here are some guides
1
2

Adding multiple goals to an action is not possible (I think).

+1
source

You can create a singleton object, and the objects will request this object from the class object (as Apple does). Add the same UIControl methods to your class and register the object and other information in a mutable dictionary, keep a weak reference to the objects, registering by wrapping the objects in the NSValue object using the ** valueWithNonretainedObject: ** method.

0
source

All Articles