Solve NSTimer Memory leakage problem, nstimer Leakage
Creating a timer will execute some operations after a certain interval. Generally, you will create a timer in this way. In this way, self references the timer and the timer references the self, it causes loop reference and eventually causes memory leakage. If the timer is downloading, the download will continue.
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startTimer) userInfo:nil repeats:YES];
Solution: first, create an nstsuppclassification: NSTimer + eocBlockSupports code is as follows. We can see that it places the operations to be executed by the timer in the block parameter, when a timer is returned, the block is passed to userInfo. When the timer is executed, the timer obtains the block of userinfo.
/// NSTimer + eocBlockSupports. h # import <Foundation/Foundation. h> @ interface NSTimer (eocBlockSupports)
// Class method returns an NSTimer Instance Object + (NSTimer *) eocScheduledTimerWithTimeInterval :( NSTimeInterval) timeInterval block :( void (^) () block repeats :( BOOL) repeat; @ end /// NSTimer + eocBlockSupports. m # import "NSTimer + eocBlockSupports. h "@ implementation NSTimer (eocBlockSupports) + (NSTimer *) blocks :( NSTimeInterval) timeInterval block :( void (^) () block repeats :( BOOL) repeat {return [self limit: timeInterval target: self selector: @ selector (startTimer :) userInfo: [block copy] repeats: repeat];} // method executed by the timer + (void) startTimer :( nsttimer *) timer {void (^ block) () = timer. userInfo; if (block) {block () ;}@ end
After the NSTimer category is created, the code for creating a scheduled NSTimer is as follows: You must weaken self; otherwise, the issue of circular reference cannot be solved.
_ Weak typeof (self) weakSelf = self;
Self. timer = [NSTimer eocScheduledTimerWithTimeInterval: 1.0 block: ^ {
[WeakSelf startTimer];
} Repeats: YES];