UIView has a setNeedsDisplay
method that one can call several times within the same event loop, safe in the knowledge that the redrawing work will happen soon, and only the once.
Is there a generic mechanism for this sort of behaviour Cocoa? A way of of saying, "Queue a selector as many times as you like, when it's time, the selector will run once & clear the queue."
I know I could do this with some kind of state tracking in my target, or with an NSOperationQueue. I'm just wondering if there's a lightweight approach I've missed.
(Of course, the answer may be, "No".)
setNeedsDisplay
is not a good example of what you're describing, since it actually does run every time you call it. It just sets a flag. But the question is good.One solution is to use NSNotificationQueue with
NSNotificationCoalescingOnName
.Another solution is to build a trampoline to do the coalescing yourself. I don't have a really good blog reference for trampolines, but here's an example of one (LSTrampoline). It's not that hard to build this if you want to coalesce the messages over a period of time. I once built a trampoline with a
forwardInvocation:
similar to this:This actually coalesces all messages to the object over the time period (not just matching messages). That's all I needed for the particular problem. But you could expand on this to keep track of which selectors are being coalesced, and check your invocations to see if they match "sufficiently."
To get this to run on the next event loop, just set timeout to 0.
I keep meaning to blog about trampolines. Required shilling: My upcoming book covers trampolines in Chapter 4 and Chapter 20.
This is not exactly how
UIView
is doing it becausesetNeedsDisplay
simply sets a flag and the internalUIView
mechanism makes sure to calldrawRect:
after setting up the drawing environment, but this is a generic way and doesn't require any special state tracking in your class.