3
votes

By default an object returnd by method alloc or copy has retain count equals to 1, so you have to release it by yourself.

But through NSTimer sample codes

// in one method start the timer (which myTimer is an Class Instance)
myTimer = [NSTimer scheduledTimerWithTimeInterval:1
                   target:self selector:@selector(method:)
                   userInfo:nil repeats:YES];

// in another method 
[myTimer invalidate];
myTimer = nil;

My question is why [NSTimer sche**] returns an object that you needn't retain, but you can access it anywhere. And you needn't release it but only invoke invalidate on it.

1

1 Answers

4
votes

The instance is retained in the run loop that it is assigned to. The retain count remains above zero until the run loop releases it. So you can access the object until that happens.

From the NSTimer docs:

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.

And then specifically:

Use the scheduledTimerWithTimeInterval:invocation:repeats: or scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: class method to create the timer and schedule it on the current run loop in the default mode.

So the method you've used works with the current run loop automatically.