I'm new in Objective C programming, I come from C++ and would better understand the ARC memory management; If I have the following situation:
-(void) test_method
{
NSTimer* t=[NSTimer ScheduledTimerWithTimeInterval:2
target:self selector;@selector(exec_method) userinfo:nil repeats:YES];
}
at the end of the method, I expected to lost the reference t, so, for the ARC, an automatic call to release and so deallocation of the NSTimer object, instead it seems that it still is in memory (the exec_method repeats its execution every 2 seconds)..or it will be deallocated when the system needs space in memory?
From Apple 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 maintain strong references to their timers, so you don’t have to maintain your own strong reference to a timer after you have added it to a run loop.
You must invalidate an NSTimer to remove it from the run loop.
In order to simplify this process, what you can do is create two methods, one to create and start the timer and one to invalidate the time. These methods would require you to declare your times as IVARs.
Swift:
let timer = NSTimer(timeInterval: 1.0, target: self, selector: "incrementCompletedUnitCount:",
userInfo: nil, repeats: true)
progress.cancellationHandler = {
timer.invalidate()
}
progress.cancel()
Objective-C
NSTimer * _studentTimer1;
-(void)startStudentTimer {
NSLog(@"***TIMER STARTED***");
_studentTimer1 = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(dowork) userInfo:nil repeats:TRUE];
}
-(void)invalidateStudentTimer1 {
[_studentTimer1 invalidate];
}
Also, for safety, you may want to place your invalidation method inside the dealloc method of your view controller.
You may also consider extra safety measures by using a weak pointer to the timer like so:
NSTimer* __weak timer = [NSTimer scheduledTimerWithTimeInterval:30.0f target: self selector:@selector(tick) userInfo:nil repeats:YES];
or as an IVAR:
NSTimer * __weak _studentTimer1;
And no, as for your last question, the time will remain in the run loop until you explicitly invalidate it, that's why you need to be careful with NSTimer and should wrap it up in as much safety as possible.