Re: Memory Management Question
Re: Memory Management Question
- Subject: Re: Memory Management Question
- From: James Bucanek <email@hidden>
- Date: Tue, 3 Jul 2007 22:33:59 -0700
Seth Pellegrino <mailto:email@hidden> wrote (Tuesday, July
3, 2007 10:13 AM -0400):
Mainly my problem is with the NSTimer class. Whenever the user
clicks pause in my application, I call -[invalidate] to stop
the timer from firing (as there seems to be no -[pause] or
similar). However, this causes the run loop to release the
timer, so whenever I try to call -[isValid], my program
crashes. As I type this, I realize that I should be also
-[retain]ing my instance of the NSTimer class, but if I do so,
is there a way to make an invalidated timer resume firing? Or
would it be better to just use a BOOL isPaused and an if statement?
Handling repeating NSTimers is a little different than most
objects. They are retained by the run loop while they are
active, and essentially become useless once stopped.
Consequently, I find that it's easier to let the run loop manage
their ownership and simply forget about it once you've stopped them.
When you need to start the timer, create it but let the run loop
retain it. In your "begin" or "resume" routine (written in mail):
if (myTimer==nil)
myTimer = [NSTimer scheduledTimerWith...];
In your "stop" or "pause" routine, simply forget the timer and
let the run loop dispose of it:
[myTimer invalidate];
myTimer = nil;
It's always safe to send messages to myTimer because either the
timer will still be valid while it's running or myTimer will be
nil once you've invalidated it.
Note that this only applies to repeating timers, which remain
valid until you invalidate it. One-shot timers either need to be
retained (because the run loop will release it once it has
fired), or simply write your code so you don't need a reference
to the timer at all.
--
James Bucanek
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden