views:

536

answers:

1

I know its fine to call a method as if it was void even though it has a return value (like printf), but what about this?

[NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(method) userInfo:nil repeats:NO];

Can I just have that floating there without using the object it returns? That's like calling [NSObject alloc] without assigning that to a pointer or anything. Is that a memory leak? The reason is I don't want to assign it to a variable (the timer) because then if I release (or autoreleaase) it gets deleted before it fires. And I don't want to use an ivar. So what should I do?

EDIT: I found out about [self performSelector:@selector(myMethod) withObject:nil afterDelay:0.3]; which is much better for this than using the timer.

+2  A: 

NSTimer created by this call is owned by current NSRunLoop object, so it is not going to be autoreleased by any autorelease pool drain. And it's wrong to release it manually. NSTimer should be removed by sending it invalidate message:

To request the removal of a timer from an NSRunLoop object, send the timer the invalidate message from the same thread on which the timer was installed. This message immediately disables the timer, so it no longer affects the NSRunLoop object. The run loop removes and releases the timer, either just before the invalidate method returns or at some later point.

So basically you should have a variable for it and use invalidate instead of release

gonzo
is there a way to just make it invalidate when it fires? It doesn't repeat.. It's working perfectly now except for if there's a memory leak.. Leaks doesn't say there's a leak, and the timer object is never assigned to a pointer or released or invalidated.
Mk12
I figured it out, I didn't know the timer passes itself as an argument. So you say I should invalidate the timer, and not release it?
Mk12
You must be right because I tried releasing after invalidating and it crashed... thanks!
Mk12
When you add a timer to a run loop, the run loop retains it. When you invalidate the timer, the run loop releases it. Therefore, unless you retained it yourself, you shouldn't release it yourself. Non-repeating timers automatically invalidate themselves:"repeatsIf YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires."
Wevah