I have a class called RunningInteger, which — on a different thread (to avoid blocking the main thread) — loops an integer ivar from 1 to 60, with 1 second between them. Hence, the whole loop takes about one minute. The ivar is provided to the outside world via a method or a readonly property.
I have a custom NSView subclass that has 60 different modes in which it can display itself.
Now, this is what I want to accomplish:
-
I have a button on the interface. When clicked, i.e. inside its action method, a new instance of
RunningIntegershould be created, and, the view should draw itself according to the ivar of this instance. -
However — and this is the catch — if the button is clicked again, the animation should reset accordingly and start all over again. This should be thread-safe, and no memory should leak, and no threads should get stacked up.
Any ideas about how to accomplish this?
There are two particular (among probably many other) issues that go hand-in-hand with this:
-
Obviously, it’s not a good design to just let the threads keep stacking up, even if we know they go away after 60 seconds. After all, what if the 60 seconds were 1 hour? (That’s a possiblity.)
-
How do we make sure that only the most recently created instance of
RunningIntegergets to update the view’s display (setNeedsDisplay:YES)?
Make RunningInteger a singleton:
Then simply reset your counter when the button presses the button. Use a timer to increase the singleton counter at regular interval. Then access the singleton from your view to know what to display.