Troubleshoot memory leaks in iOS due to timers

Source: Internet
Author: User

Call the Timer method once:

[CPP] view plain copy mytimer = [Nstimer scheduledtimerwithtimeinterval:1.5 target:self selector: @selector (   Scrolltimer) Userinfo:nil Repeats:no]; Do not repeat, call only once. The timer will automatically stop running once it is run

Repeat Call timer method: [CPP] view plain Copy timer = [Nstimer scheduledtimerwithtimeinterval:1.0 target:self selector: @sele   ctor (function:) Userinfo:nil Repeats:yes];   The function method is run once every 1 seconds. Note: When you set the counter's repeats to Yes, the self's reference count is added by 1. as a result, self (that is, Viewcontroller) may not release, so you must stop the counter timer when viewwillappear, or it may cause a memory leak.

Stop the timer from running, but this is a permanent stop:

[CPP] view plain copy//cancel timer [timer invalidate];


To do this: stop first and then run the timer again in some case, you can use the following method:

First off the timer can not use the above method, you should use the following method:

[CPP] view plain copy//close timer [MyTimer setfiredate:[nsdate distantfuture]];
You can then turn on this timer by using the following method:

[CSharp] View plain copy//open timer [MyTimer setfiredate:[nsdate Distantpast]];
Example: For example, turn off the timer when the page disappears, and then turn on the timer when the page opens again.

(mainly to prevent it running in the background, take up the CPU) can be implemented using the following code:

[CPP] view plain copy//page will enter the foreground, turn on timer-(void) Viewwillappear: (BOOL) Animated {//open timer [Scrollvie   W.mytimer setfiredate:[nsdate Distantpast]]; }//page disappears, enter the background does not display the page, turn off timer-(void) Viewdiddisappear: (BOOL) Animated {//close timer [Scrollview.mytimer Setfir   Edate:[nsdate Distantfuture]]; }

OK, it's done.

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.