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. Timer runs once and stops automatically
To invoke the Timer method repeatedly:
[CPP]View Plain Copy
- Timer = [Nstimer scheduledtimerwithtimeinterval:1.0 target:self selector: @selector (function:) Userinfo:nil repeats: YES];
- //Run the function method once every 1 seconds.
Note: When you set the counter's repeats to Yes, the reference count of self is incremented by 1. as a result, self (that is, Viewcontroller) cannot be released, so the counter timer must be stopped at viewwillappear time, otherwise the memory leak may result.
Stop the timer from running, but this is a permanent stop: (note: after the stop, be sure to empty the timer, otherwise there is no release .) Don't believe me? You try it yourself ~)
[CSharp]View Plain Copy
- //Cancel Timer
- [Timer invalidate];
- Timer = nil;
To achieve this: stop first, and then in some cases turn on the timer again, you can use the following method:
First off the timer cannot use the method above, should use the following method:
[CPP]View Plain Copy
- //Off timer
- [MyTimer setfiredate:[nsdate distantfuture];
then you can use the following method to open this timer again:
[CSharp]View Plain Copy
- //Turn on timer
- [MyTimer setfiredate:[nsdate Distantpast];
Example: For example, when the page disappears, turn off the timer, and then when the page opens again, turn on the timer.
(primarily to prevent it from 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 the timer
- -(void ) Viewwillappear: ( bool ) animated
- {
- //Turn on timer
- [Scrollview.mytimer setfiredate:[nsdate Distantpast];
- }
- //page disappears, go backstage do not show this page, turn off timer
- -(void ) Viewdiddisappear: ( bool ) animated
- {
- //Off timer
- [Scrollview.mytimer setfiredate:[nsdate distantfuture];
- }
Timer Nstimer in iOS