Code:
#import "ViewController.h"@interfaceViewcontroller () @property (Strong, nonatomic) Nstimer*timer;- (void) DoSomething: (Nstimer *) timer;@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; //Programming Tips//A timer maintains a strong reference to its target. //This means is as long as a timer remains valid, its target is not being deallocated. //as a corollary, this means, it does does sense for a timer's target to try and invalidate the timer in its DEA Lloc method,//The Dealloc method won't be invoked as long as the timer is valid. //Target parameter//The object to which to send the message specified by Aselector when the timer fires. //The timer maintains a strong reference to this object until it (the timer) is invalidated.Nstimer *timer = [Nstimer timerwithtimeinterval:1target:self selector: @selector (dosomething:) Userinfo:nil Repeats:yes]; //The receiver retains atimer. //to remove a timer from all run loops modes on which it's installed, send an invalidate message to the timer.[[Nsrunloop Currentrunloop] Addtimer:timer formode:nsrunloopcommonmodes]; Self.timer=timer;}- (void) DoSomething: (Nstimer *) Timer {NSLog (@"%s", __func__);}- (void) dealloc {NSLog (@"%s", __func__); [Self.timer invalidate];}@end
In the above code, since the timer retains a strong reference to its target within its validity period, target itself is the current Viewcontroller and a strong reference to the timer is generated by a property decorated with the strong modifier, resulting in a circular reference.
And in this case, because Runloop refers to the timer that is added to it, it produces a circular reference that can never be broken by itself.
Because of the existence of a circular reference, the Dealloc method is not invoked even if the current Viewcontroller is ejected from the navigation controller's navigation stack. So in the Dealloc method, it makes no sense to call the Invalidate method of the timer.
One possible way is to rewrite Viewcontroller's viewwilldisappear: or Viewdiddisappear: Method that invokes the Invalidate method of the timer in its method body, This relieves the timer from the strong reference to target, Viewcontroller, and eventually breaks the circular reference.
Code-Modified version:
#import "ViewController.h"@interfaceViewcontroller () @property (Strong, nonatomic) Nstimer*timer;- (void) DoSomething: (Nstimer *) timer;@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; Nstimer*timer = [Nstimer timerwithtimeinterval:1target:self selector: @selector (dosomething:) Userinfo:nil Repeats:yes]; [[Nsrunloop Currentrunloop] Addtimer:timer formode:nsrunloopcommonmodes]; Self.timer=timer;}- (void) DoSomething: (Nstimer *) Timer {NSLog (@"%s", __func__);}- (void) Viewwilldisappear: (BOOL) animated {[Super viewwilldisappear:animated]; NSLog (@"%s", __func__); [Self.timer invalidate];}- (void) dealloc {NSLog (@"%s", __func__);}@end
Nstimer and circular references