NSTimer invalidate not working - iphone

I am trying to create an explosion on the iphone screen which gets bigger fast, then goes away. Why is this timer not stopping?
NSTimer *explosion = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(explosion) userInfo:nil repeats:YES];
-(void)explosion {
image.image = [UIImage imageNamed:#"explosion.png"];
expsize = expsize + 2.5;
image.frame = CGRectMake(image.frame.origin.x, image.frame.origin.y, expsize, expsize);
if (expsize > 60) {
NSLog(#"%f",expsize);
[explosion invalidate];
explosion = nil;
}
}

You are most likely invalidating the wrong timer.
You create a local variable named explosion that has the same name as the instance variable.
Avoid declaring instance variables and local variables with the same name!

I'd suggest that you use the form of selector that the NSTimer doc calls for: - (void)timerFireMethod:(NSTimer*)theTimer. The you can invalidate "theTimer" and be sure you're invalidating the right one.
Also, of course, if "explosion" is declared as a property, then there will be two methods in the class named "explosion", and no real clue as to which one is getting called.

It's hard to be certain, because it's not clear whether this is exactly your code, but you have two variables named explosion, and one of them has an NSTimer assigned to it; the other (which seems to be an ivar) is nil.
// Variable local to whatever method this is in
NSTimer *explosion = [NSTimer scheduledTimerWithTimeInterval:0.1...
if (expsize > 60) {
NSLog(#"%f",expsize);
// Other variable named "explosion" does not exist.
// This is an ivar? Has not been set.
[explosion invalidate];
Assuming you've got explosion declared as a property (and there is no reason not to), you should fix this by using the setter when you create the timer:
[self setExplosion:[NSTimer scheduledTimerWithTimeInterval:...]];
Now the ivar has the timer instance and you can use it to invalidate the timer.
Also, note that your timer's method is incorrect; it must take one parameter which is a pointer to the timer. You can also use this pointer to invalidate the timer when it fires.
- (void) fireExplosion: (NSTimer *)tim {
//...
if( expsize > 60 ){
[tim invalidate];
//...
}
}
Finally, you have one last naming problem; if your property is called explosion, the convention in Cocoa is that the accessor should have the same name, but you have used explosion for the method that your timer calls. This could cause hard-to-track problems later. You should rename the timer method as I have here, using a verb indicating that something is happening.

If you are declaring explosion how you posted in your example then you are shadowing your instance variable explosion. As a word of advice you should use a naming convention for instance variables such as an underscore prefix. Now keeping track of the timer is not required if you only invalidate it after it fires. You could just take an extra parameter on the explosion method that would be the timer explosion:(id)timer. Otherwise you can do the following.
#interface X : NSObject
{
NSTimer *_explosion;
}
#end
And when you go to declare it in your code do the following
...
[_explosion invalidate];
[_explosion release];
//There is a whole 'nother debate on whether or not to retain a scheduled timer
//but I am a stickler for ownership so remember to release this in dealloc
_explosion = [[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:#selector(explosion)
userInfo:nil
repeats:YES] retain];
...
-(void)explosion {
image.image = [UIImage imageNamed:#"explosion.png"];
expsize = expsize + 2.5;
image.frame = CGRectMake(image.frame.origin.x, image.frame.origin.y, expsize, expsize);
if (expsize > 60) {
NSLog(#"%f",expsize);
[_explosion invalidate];
[_explosion release];
_explosion = nil;
}
}

Related

iPhone NSTimer change repeat time

I have a static method in which I setup NSTimer, but sometimes I need to change repeat time. How to do that if I work with static method? Should be something like this:
+ (void)setupTimer:(BOOL)updateTime newTime:(int)time {
NSTimer *timer;
if (updateTime) {
[timer invalidate];
timer = nil;
}
timer = [NSTimer scheduledTimerWithTimeInterval:time
target:self
selector:#selector(myMethod:)
userInfo:nil
repeats:YES];
}
But it's not working...and I know that I cannot invalidate in this case my timer...but also I cannot use NSTimer declared as member of class in static method...How to be ? thanks....
Just prefix the variable with static.
static NSTimer *timer;
If you overwrite the timer variable, you should invalidate it first, because otherwise you'll have a timer running, that you don't have access to anymore.
I think you should be able to write this without static functions but you can also do this using static functions. If there should be only one instance of that class then use a singleton-pattern.
for doing this with static functions then just use
static NSTimer *timer
but you also have to retain your new and also release the old timer because the function scheduledTimer... allocs an NSTimerinstance but also autoreleases it. If dont retain that timer then the timer will be deallocated later and will afaik not call your method.

NSTimers causing leaks

I've read up a lot about NSTimers, but I must be doing something very wrong with them, because it's practically all the leaks that show up in the Leaks Instrument. The "Responsible Frame" column says -[NSCFTimer or +[NSTimer(NSTimer).
So here's how I have an NSTimer set up in my main menu. I shortened it up to just show how the timer is setup.
.h -
#interface MainMenu : UIView {
NSTimer *timer_porthole;
}
#end
#interface MainMenu ()
-(void) onTimer_porthole:(NSTimer*)timer;
#end
.m -
(in initWithFrame)
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
timer_porthole = [[NSTimer scheduledTimerWithTimeInterval:.05
target:self
selector:#selector(onTimer_porthole:)
userInfo:nil
repeats:YES] retain];
}
return self;
}
When leaving the view, it kills the timers:
-(void) kill_timers{
[timer_porthole invalidate];
timer_porthole=nil;
}
And of course, dealloc:
- (void)dealloc {
[timer_porthole invalidate];
[timer_porthole release];
timer_porthole = nil;
[super dealloc];
}
Don't call retain on your NSTimer!
I know it sounds counter-intuitive but when you create the instance it's automatically registered with the current (probaby main) threads run loop (NSRunLoop). Here's what Apple have to say on the subject...
Timers work in conjunction with run
loops. To use a timer effectively, you
should be aware of how run loops
operate—see NSRunLoop and Threading
Programming Guide. Note in particular
that run loops retain their timers, so
you can release a timer after you have
added it to a run loop.
Once scheduled on a run loop, the
timer fires at the specified interval
until it is invalidated. A
non-repeating timer invalidates itself
immediately after it fires. However,
for a repeating timer, you must
invalidate the timer object yourself
by calling its invalidate method.
Calling this method requests the
removal of the timer from the current
run loop; as a result, you should
always call the invalidate method from
the same thread on which the timer was
installed. Invalidating the timer
immediately disables it so that it no
longer affects the run loop. The run
loop then removes and releases the
timer, either just before the
invalidate method returns or at some
later point. Once invalidated, timer
objects cannot be reused.
Quotes are sourced from Apple's NSTimer class reference.
So your instantiation becomes...
timer_porthole = [NSTimer scheduledTimerWithTimeInterval:.05
target:self
selector:#selector(onTimer_porthole:)
userInfo:nil
repeats:YES];
And now that you're no longer holding the reference to the instance you wont want the release call in your dealloc method.
I've seen you already accepted an answer but there are two things here that I wanted to rectify:
It's not needed to retain a scheduled timer but it doesn't do any harm (as long as you release it when it's no longer needed). The "problematic" part of a timer/target relationship is that...
a timer retains its target. And you've decided to set that target to self.
That means — retained or not — the timer will keep your object alive, as long as the timer is valid.
With that in mind, let's revisit your code from bottom to top:
- (void)dealloc {
[timer_porthole invalidate]; // 1
[timer_porthole release];
timer_porthole = nil; // 2
[super dealloc];
}
1 is pointless:
If timer_porthole was still a valid timer (i.e. scheduled on a runloop) it would retain your object, so this method wouldn't be called in the first place...
2 no point here, either:
This is dealloc! When [super dealloc] returns, the memory that your instance occupied on the heap will be freed. Sure you can nil out your part of the heap before it gets freed. But why bother?
Then there is
-(void) kill_timers{
[timer_porthole invalidate];
timer_porthole=nil; // 3
}
3 given your initializer (and as others have pointed out) you are leaking your timer here; there should be a [timer_porthole release] before this line.
PS:
If you think it all over, you'll see that retaining the timer (at least temporarily) creates a retain-cycle. In this particular case that happens to be a non-issue which is resolved as soon as the timer is invalidated...
You missed [timer_porthole release]; call in your kill_timers method. If you call kill_timers before dealloc method is called, you set timer_porthole to nil, but you did not release it.

Repeating NSTimer, weak reference, owning reference or iVar?

I thought I would put this out here as a separate question from my previous
retaining-repeating-nstimer-for-later-access as the discussion has moved forward making a new question clearer than yet another EDIT:
The scenario is an object creates a repeating NSTimer, lets say in viewDidLoad, once created the NSTimer needs to stay around so it can be accessed by other methods.
NSTimer *ti = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(updateDisplay:)
userInfo:nil
repeats:YES];
I understand that when created the runloop takes ownership of the NSTimer and ultimately stops, removes and releases the NSTimer when [ti invalidate]; is called.
By virtue of the fact that we need to access the NSTimer in more than one method we need some way to hold a reference for future use, the revised question is:
// (1) Should the NSTimer be held using an owning reference (i.e.)
#property(nonatomic, retain) NSTimer *walkTimer;
[self setWalkTimer: ti];
...
...
// Cancel method
[[self walkTimer] invalidate;
[self setWalkTimer:nil];
...
...
// dealloc method
[walkTimer release];
[super dealloc];
.
// (2) Should the NSTimer be held using a weak reference (i.e.)
#property(nonatomic, assign) NSTimer *walkTimer;
[self setWalkTimer: ti];
...
...
// Cancel method
[[self walkTimer] invalidate];
[self setWalkTimer:nil];
...
...
// dealloc method
[super dealloc];
.
// (3) Use an iVar and rely on the runLoop holding (i.e. retaining) the timer
NSTimer *walkTimer;
NSTimer *walkTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(updateDisplay:)
userInfo:nil
repeats:YES];
...
...
// Cancel method
[walkTimer invalidate];
walkTimer = nil;
.
// (4) Something not listed above ...
I am happy for just (1) (2) (3) or (4) as a lot of discussion regarding which is best has already been written on the Other thread. There does seem to be a lot of conflicting answers so I hope this more specific question will help focus on what might be best practice in this situation.
EDIT:
As a side note in the Apple NSTimer Class Reference 4 out of 5 of the sample code projects use NSTimers that are assigned** to a retained property. Here is an example of what the class reference examples show:
#property (nonatomic, retain) NSTimer *updateTimer;
updateTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:#selector(updateCurrentTime) userInfo:p repeats:YES];
...
...
// Cancel
[updateTimer invalidate];
updateTimer = nil;
...
...
// Dealloc method
[super dealloc];
[updateTimer release];
** It should be noted that in the examples Apple are assigning the iVar directly and not using the property setter.
After giving it all some more thought and finding an important flaw in my reasoning, I've come to a different conclusion:
It doesn't matter much, whether you hold an owning or a non-owning reference to a timer that you need to invalidate. It is completely a matter of taste.
The deal breaker is, what the target of the timer is:
If the object that creates a timer is its target, managing that object's lifetime becomes more fragile: it cannot simply be retain/release managed, instead you need to ensure that the client that holds the last reference to this object makes it invalidate the timer before it disposes of it.
Let me illustrate the situation with a couple of sort-of-object-graphs:
You start in a state from which you setup the timer and set yourself as the target. Setup of the Timer: yourObject is owned by someClientObject. In parallel exists the current run-loop with an array of scheduledTimers. the setupTimer method is called upon yourObject:
The result is the following initial state. In addition to the former state yourObject now has a reference (owned or not) to the workTimer, which in turn owns yourObject. Furthermore, workTimer is owned by the run-loops scheduledTimers array:
So now you'll use the object, but when you're done with it and simply release it, you'll end up with simple release leak: after someClientObject disposes of yourObject through a simple release, yourObject is disassociated from the object-graph but kept alive by workTimer. workTimer and yourObject are leaked!
Where you leak the object (and the timer) because the runloop keeps the timer alive, which — in turn — keeps an owning reference to your object.
This can be avoided if yourObject is only ever owned by one single instance at a time, when it is properly disposed of proper disposal through cancellation: before disposing of yourObject through release, someClientObject calls the cancelTimer method on yourObject. Within that method, yourObject invalidates workTimer and (if it owned workTimer) disposes of workTimer through release:
But now, how do you resolve the following situation?
Multiple Owners: Setup like in the initial state, but now with multiple independent clientObjects that hold references to yourObject
There is no easy answer, I am aware of! (Not that the latter has to say much, but...)
So my advice is...
Don't make your timer a property/don't provide accessors for it! Instead, keep it private (with the modern runtime I think you could go so far as to define the ivar in a class extension) and only deal with it from one single object. (You may retain it, if you feel more comfortable doing so, but there is absolutely no need for it.)
Caveat: If you absolutely need to access the timer from another object, make the property retain the timer (as that is the only way to avoid crashes caused by clients that directly invalidated the timer they accessed) and provide your own setter. Rescheduling a timer is — in my opinion — not a good reason to break encapsulation here: provide a mutator if you need to do that.
Set the timer up with a target other than self. (There are plenty of ways doing so. Maybe through writing a generic TimerTarget class or — if you can use it — through a MAZeroingWeakReference?)
I apologize for being a moron in the first discussion and want to thank Daniel Dickison and Rob Napier for their patience.
So here is the way I am going to handle timers from now on:
// NSTimer+D12WeakTimerTarget.h:
#import <Foundation/NSTimer.h>
#interface NSTimer (D12WeakTimerTarget)
+(NSTimer *)D12scheduledTimerWithTimeInterval:(NSTimeInterval)ti weakTarget:(id)target selector:(SEL)selector userInfo:(id)userInfo repeats:(BOOL)shouldRepeat logsDeallocation:(BOOL)shouldLogDealloc;
#end
// NSTimer+D12WeakTimerTarget.m:
#import "NSTimer+D12WeakTimerTarget.h"
#interface D12WeakTimerTarget : NSObject {
__weak id weakTarget;
SEL selector;
// for logging purposes:
BOOL logging;
NSString *targetDescription;
}
-(id)initWithTarget:(id)target selector:(SEL)aSelector shouldLog:(BOOL)shouldLogDealloc;
-(void)passthroughFiredTimer:(NSTimer *)aTimer;
-(void)dumbCallbackTimer:(NSTimer *)aTimer;
#end
#implementation D12WeakTimerTarget
-(id)initWithTarget:(id)target selector:(SEL)aSelector shouldLog:(BOOL)shouldLogDealloc
{
self = [super init];
if ( !self )
return nil;
logging = shouldLogDealloc;
if (logging)
targetDescription = [[target description] copy];
weakTarget = target;
selector = aSelector;
return self;
}
-(void)dealloc
{
if (logging)
NSLog(#"-[%# dealloc]! (Target was %#)", self, targetDescription);
[targetDescription release];
[super dealloc];
}
-(void)passthroughFiredTimer:(NSTimer *)aTimer;
{
[weakTarget performSelector:selector withObject:aTimer];
}
-(void)dumbCallbackTimer:(NSTimer *)aTimer;
{
[weakTarget performSelector:selector];
}
#end
#implementation NSTimer (D12WeakTimerTarget)
+(NSTimer *)D12scheduledTimerWithTimeInterval:(NSTimeInterval)ti weakTarget:(id)target selector:(SEL)selector userInfo:(id)userInfo repeats:(BOOL)shouldRepeat logsDeallocation:(BOOL)shouldLogDealloc
{
SEL actualSelector = #selector(dumbCallbackTimer:);
if ( 2 != [[target methodSignatureForSelector:aSelector] numberOfArguments] )
actualSelector = #selector(passthroughFiredTimer:);
D12WeakTimerTarget *indirector = [[D12WeakTimerTarget alloc] initWithTarget:target selector:selector shouldLog:shouldLogDealloc];
NSTimer *theTimer = [NSTimer scheduledTimerWithTimeInterval:ti target:indirector selector:actualSelector userInfo:userInfo repeats:shouldRepeat];
[indirector release];
return theTimer;
}
#end
Original (for full disclosure):
You know my opinion from your other post:
There is little reason for an owning reference of a scheduled timer (and bbum seems to agree).
That said, your options 2, and 3 are essentially the same. (There is additional messaging involved in [self setWalkTimer:nil] over walkTimer = nil but I'm not sure if the compiler won't optimize that away and access the ivar directly, but well...)
I generally manage the invalidate inside of the accessor so that you never get surprised by a timer accessing you after you think you got rid of it:
#property(nonatomic, retain) NSTimer *walkTimer;
[self setWalkTimer: ti];
- (void)setWalkTimer:(NSTimer *)aTimer
{
if (aTimer != walkTimer_)
{
[aTimer retain];
[walkTimer invalidate];
[walkTimer release];
walkTimer = aTimer;
}
}
...
...
// Cancel method
[self setWalkTimer:nil];
...
...
// Make a new timer, automatically invalidating the old one
[self setWalkTimer:[... a new timer ...]]
...
...
// dealloc method
[walkTimer_ invalidate];
[walkTimer_ release];
[super dealloc];

Correct way to release NSTimer?

What is the correct way to release a NSTimer in my dealloc method ? It was created with the following code ?
-(void)mainTimerLoop {
mainTimer = [NSTimer scheduledTimerWithTimeInterval:1/10
target:self
selector:#selector(gameLoop)
userInfo:nil
repeats:YES];
}
Thanks
The way you're doing it, you won't ever hit dealloc. A timer retains its target. In this case, that means the timer has retained you. It will not release you until it is invalidated. Since you created the timer, you must also invalidate it at some point prior to dealloc, because the timer's retain will prevent your object's being dealloced.
You have two options:
find another place to invalidate the timer (view goes offscreen, application is terminating, what have you)
set something else as the timer's target.
As an example of the latter:
#interface GameLoopTimerTarget : NSObject {
id owner; /* not retained! */
}
- (id)initWithOwner:(id)owner;
- (void)timerDidFire:(NSTimer *)t;
#end
#implementation GameLoopTimerTarget
- (id)initWithOwner:(id)owner_ {
self = [super init];
if (!self) return nil;
owner = owner_;
return self;
}
- (void)timerDidFire:(NSTimer *)t {
#pragma unused (t)
[owner performSelector:#selector(gameLoop)];
}
#end
/* In your main object… */
/* assume synthesized:
#property (retain, NS_NONATOMIC_IPHONE_ONLY) GameLoopTimer *mainTimerTarget; */
- (void)mainTimerLoop {
self.mainTimerTarget = [[[GameLoopTimerTarget alloc] initWithOwner:self] autorelease];
mainTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 target:self.mainTimerTarget selector:#selector(timerDidFire:) userInfo:nil repeats:YES];
}
- (void)dealloc {
/* other stuff */
[timer invalidate], timer = nil;
[mainTimerTarget release], mainTimerTarget = nil;
/* more stuff */
[super dealloc];
}
Notice how the time interval is 1.0/10.0 - this could also be written 0.1, but it cannot be written 1/10, as that division will truncate to 0.0.
Also notice how this breaks the retain cycle:
Both you and your timer retain the timer target.
You hit dealloc at the normal time.
You then invalidate the timer and release the timer target.
The timer target is then deallocated.
A valid NSTimer is retained by the run loop, which, if it is repeating, will be forever or until you invalidate it. You shouldn't release it, since, in your example code, you did not explicitly retain it. If you invalidate it, it will no longer be retained by the run loop, and will be autoreleased.
This might be OK for a repeating timer, but is dangerous for a one-shot timer, since it might end being released before you ever access it to see if it's valid and/or try to invalidate it (which would lead to a bad-access app crash). Therefore if you plan on, in any way, looking at a timer variable after it's creation (including to check it, invalidate it and/or release it), it might be a good practice to explicitly retain it somewhere in your app, and then release it and set it to nil after it's invalid and you are done with it.
You can release it and set it to nil in one statement if you declare it as a retain property. Then you can write:
self.timer = nil;
you have a really good answer about NSTimer here How do I use NSTimer? there they talk about stoping a repeating NSTimer doing
[myTimer invalidate];
I think the best advice here is -
Do not retain the NSTimer instance, and do not release it.
As soon as it is scheduled on an NSRunloop (current runloop in the OP's example, an NSTimer is retained by the runloop until being invalidated, or until the runloop stops.
What you should be doing, is to invalidate your timer at the right time - and on the same thread where you created and scheduled it.
Keep in mind, also, that NSTimer retains its target, and won't let the target "die" before it dies itself. design your code so that you don't have a retain cycle that will prevent the releasing of both your object (holding the timer) and the timer (holding you object).
You don't need to release it because it will be autoreleased. Anything created by a convenience method (i.e. you don't call alloc yourself) is the responsibility of the called function to memory manage, which usually means that it will call autorelease on the object it creates before it returns it.
I would assign the timer to a property with the retain keyword though to make sure it doesn't get deallocated on you. Generally autoreleased objects are deallocated in the event loop if they don't have any retains.

NSTimer not stopping

I have a Class with a NSTimer *myTimer; variable. At some point I do:
myTimer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:#selector(doStuff) userInfo:nil repeats: YES];
further, I have a method:
- (void)doStuff
{
if(myTimer)
{
//do stuff
}
}
and I stop my timer when the class is released through:
- (void)dealloc
{
if (myTimer) { //if myTimer==nil it already has been stopped in the same way
[myTimer invalidate];
myTimer = nil;
}
}
Now, the problem is that when I release the class the timer goes on and on and on firing the event anyway. Am I doing something wrong? It seems the dealloc method is never called, otherwise myTimer would be nil and even if the selector is fired it would not go into the if(myTimer)
This will never work, because timers retain their target, which means your dealloc method will never get invoked until after you've invalidated the timer.
For more info, see the NSTimer documentation and this blog post on "Dangerous Cocoa Calls"
Have you tried the handy debugger tools at your disposal? What happens if you set a breakpoint in your dealloc method? Also, you should post more context around your creation. Is it possible you're creating the timer more than once, thereby replacing the original (but not invalidating it) and leaving it out there to fire at will?