A number of Cocoa Touch classes use a coalescing event design pattern. UIViews , for example, has a setNeedsLayout method that calls layoutSubviews in the very near future. This is especially useful in situations where several properties affect the layout. In the customizer for each property, you can call [self setNeedsLayout] , which will provide a layout update, but will prevent many (potentially costly) layout updates if several properties change at once or even if one property has been changed several times within the same iteration of the launch cycle. Other expensive operations, such as a pair of setNeedsDisplay and drawRect: methods, follow the same pattern.
What is the best way to implement such a template? In particular, I would like to bind a number of dependent properties to an expensive method that needs to be called once to iterate through the execution cycle if the property has changed.
Possible solutions :
Using CADisplayLink or NSTimer , you can get something similar, but both of them seem more involved than necessary, and I'm not sure that the consequences for adding this large number of objects (especially timers) will be. In the end, performance is the only reason do something like this.
In some cases, I used something like this:
- (void)debounceSelector:(SEL)sel withDelay:(CGFloat)delay { [NSObject cancelPreviousPerformRequestsWithTarget:self selector:sel object:nil]; [self performSelector:sel withObject:nil afterDelay:delay]; }
This works great in situations where user input should trigger an event only with continuous action or in such things. This seems awkward when we want to ensure that there is no delay in triggering the event, instead we just want to combine calls within a single execution loop.
source share