Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top