I'm using an NSTimer
like this:
timer = [NSTimer scheduledTimerWithTimeInterval:30.0f target:self selector:@selector(tick) userInfo:nil repeats:YES];
Of course, NSTimer
retains the target which creates a retain cycle. Furthermore, self
isn't a UIViewController so I don't have anything like viewDidUnload
where I can invalidate the timer to break the cycle. So I'm wondering if I could use a weak reference instead:
__weak id weakSelf = self;
timer = [NSTimer scheduledTimerWithTimeInterval:30.0f target:weakSelf selector:@selector(tick) userInfo:nil repeats:YES];
I've heard that the timer must be invalidated (i guess to release it from the run loop). But we could do that in our dealloc, right?
- (void) dealloc {
[timer invalidate];
}
Is this a viable option? I've seen a lot of ways that people deal with this issue, but I haven't seen this.
See Question&Answers more detail:os