When setting up a timed execution using NSDate, NSTimer, and NSRunLoop, which one do I need to not release before the action in complete?
-
30-09-2019 - |
Question
Here's the part of the code dealing with it:
NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:1.0+index];
NSTimer *timer = [[NSTimer alloc] initWithFireDate:fireDate
interval:0.5
target:self
selector:@selector(countedtargetMethodGlow:)
userInfo:nil
repeats:NO];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
[timer release];
But it's in a loop, so I'll be making a buncha these, and I don't know what I need to leave alone for the firing not to be messed up.
Solution
Every timer object you add to a run loop is retained by the run loop until it's invalidated (effectively indicating that the run loop is taking "ownership" of the timer while it needs it). So you can release any of those timers without affecting how they're scheduled on the run loop. If you need them for some independent purpose you should not release them, so they're guaranteed to still be around for you even if the run loop has finished with them.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow