Retaining repeating NSTimer for later access?

前端 未结 3 1490
隐瞒了意图╮
隐瞒了意图╮ 2021-01-28 04:53

I am creating an NSTimer in the createTimer method that I want to refer back to in the later cancelTimer method. To facilitate this I am taking ownersh

3条回答
  •  粉色の甜心
    2021-01-28 05:16

    You release before you call invalidate. That means by the time you call invalidate, you've already relinquished ownership of the timer. In practice, you end up calling invalidate on a deallocated timer instance.

    What you should do is call invalidate before you call release. Since you are using a retained property, you can just set the property to nil:

    // Schedule the timer.
    self.walkTimer = [NSTimer scheduledTimerWith...];
    
    // Cancel the timer.
    [self.walkTimer invalidate];
    self.walkTimer = nil;
    

    Update to clear up any confusion regarding memory management

    It's important to keep in mind the Memory Management Rules of Objective-C — you own an object if you call alloc, copy or retain on it, and if you own an object, you have to eventually call release. In this case, setWalkTimer: retains the timer because the property is declared as retain — that means you own the timer and must call release on it down the road. The invalidate method does not count as relinquishing ownership of the timer.

    When you schedule a timer, the run loop retains it, and when the timer fires or is invalidated, the run loop releases it. But really, you don't need to know that — it's an implementation detail. The call to release by invalidate is only to balance the retain when the timer was scheduled on the run loop.

提交回复
热议问题