Solve NSTimer Memory leakage problem, nstimer Leakage

Source: Internet
Author: User

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];

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.