Detailed usage of nstimer

Source: Internet
Author: User
Tags response code
Nstimer detailed settings 1: http://blog.csdn.net/davidsph/article/details/7899483NSTimer detailed Settings 2: http://blog.csdn.net/davidsph/article/details/7899731 1 ,,,,,

First, let's talk about my business needs. Recently I am working on a small project and need to use the timer function. During the nstimer class, there were some minor problems, but I finally made my own efforts, finally. I want to sum up my learning and understanding about nstimer.

Let's talk about it later.

The interface element is very simple. Two uibutton start and pause, and 20 indicates the Start countdown. The final result is that when you press the start button, the countdown starts to run, and when you press the pause button, the timer stops the countdown. When the countdown is 0, a dialog box is displayed, prompting that the time has reached.

 

The business needs are very simple, but there are some small errors in my implementation. The primary cause is that the primary key cannot be clicked multiple times, or the START key cannot be clicked multiple times. I believe that at the beginning, the nstimer contacts will also encounter these problems.

 

Directly Add the following code:

In the. h file of the controller class

@ Interface sdsviewcontroller: uiviewcontroller <uialertviewdelegate>

// Define a timer as an instance variable
@ Property (nonatomic, retain) nstimer * timer;

// Display the current countdown status
@ Property (retain, nonatomic) iboutlet uilabel * timedisplay;

// Start button, response action
-(Ibaction) starttime :( ID) sender;

// Pause the Response Action
-(Ibaction) stoptime :( ID) sender;

@ End



Key code in. m

Response code of the Start button:

-(Ibaction) starttime :( ID) sender {

 

// If the timer object does not exist, create and start

If (! _ Timer ){

// Create a timer, which is directly added to the current message loop. Note the difference with other initialization methods.
_ Timer = [nstimer scheduledtimerwithtimeinterval: 1.0 target: Self selector: @ selector (changetimeattimedisplay) userinfo: Nil repeats: Yes];


// [_ Timer fire]; // For this fire method, It will be explained later. It is not as simple as starting a timer.

}

 

}

// Response code of the end button:

 

-(Ibaction) stoptime :( ID) sender {

If (_ timer ){
Nslog (@ "calling self. Time is true !! ");


// If the timer is running
If ([self. Timer isvalid]) {


Nslog (@ "click the stop button to cancel the timer !! ");

[Self. Timer invalidate];

// This line of code is critical
_ Timer = nil;

}

}

}

Everything is okay, and now the key points used by the analysis program.

First, let's look at the structure of the nstimer class, which is relatively simple.

Tasks

Creating a timer

// Create a timer. You can understand the following methods of the constructor:
+ Scheduledtimerwithtimeinterval: Invocation: repeats:
+ Scheduledtimerwithtimeinterval: Target: selector: userinfo: repeats:
+ Timerwithtimeinterval: Invocation: repeats:
+ Timerwithtimeinterval: Target: selector: userinfo: repeats:

// Initialization Method
-Initwithfiredate: interval: Target: selector: userinfo: repeats:

 

// Is it a timer? I'm afraid it's not that simple ????????
Firing a timer
-Fire

// Is a timer suspended? No, it is a stop, and it is clearly written.

Stopping a timer
-Invalidate

// The following information about the timer
Information about a timer
-Isvalid // whether the task is running
-Firedate // returns the date at which the specified er will fire.
-Setfiredate: // reset the timer Start Time
-Timeinterval // timer delay time
-Userinfo // Other information

---------------------------------------------------- 2 ,,,,,,,,,

First, the initialization method

+ Scheduledtimerwithtimeinterval: Invocation: repeats:
+ Scheduledtimerwithtimeinterval: Target: selector: userinfo: repeats:

These two are to create a timer and add it to the current running cycle. That is, we can understand it as follows. In this way, when a timer is initialized, the timer is automatically started after the (nstimeinterval) seconds time.

 

The following two initialization methods are different:

+ Timerwithtimeinterval: Invocation: repeats:
+ Timerwithtimeinterval: Target: selector: userinfo: repeats:

 

These two are also created, but are not added to the running loop. Class method to create the timer object without scheduling it on a run loop. after the creation, you must (after creating it, you must add the timer to a run loop manually by calling the addtimer: formode: Method of the corresponding nsunloop object .), this is the difference from the above two methods.

// Create a timer
_ Timer = [nstimer scheduledtimerwithtimeinterval: 1.0 target: Self selector: @ selector (changetimeattimedisplay) userinfo: Nil repeats: Yes];

 

 

 

_ Timer = [nst1_timerwithtimeinterval: 10 target: Self selector: @ selector (changetimeattimedisplay) userinfo: Nil repeats: Yes];
// Must be manually added to the current loop
Nsunloop * runloop = [nsunloop currentrunloop];
[Runloop addtimer: _ timer formode: nsdefaultrunloopmode];

 

The above code works the same.

 

 

About this method:

Firing a timer
-Fire

 

In fact, it does not really start a timer. From the previous initialization method, we can also see that the timer will be automatically started at the appropriate time when it is created. What does this method do.

You can use this method to fire a repeating timer without interrupting its regular Firing schedule. if the timer is non-repeating, it is automatically invalidated after firing, even if its scheduled fire date has not arrived.

This is what the official document says. It is clear in English, but we do not understand it very well. In order to thoroughly understand its functions. I did another test.

 

It's also very easy. Change the timer above.

// Create a timer during initialization

-(ID) initwithnibname :( nsstring *) nibnameornil bundle :( nsbundle *) nibbundleornil {

Self = [Super initwithnibname: nibnameornil Bundle: nibbundleornil];

If (Self ){
// Custom Initialization

// Create a timer,

_ Timer = [nst1_timerwithtimeinterval: 10 target: Self selector: @ selector (changetimeattimedisplay) userinfo: Nil repeats: Yes];

// Manually add to the loop

Nsunloop * runloop = [nsunloop currentrunloop];

[Runloop addtimer: _ timer formode: nsdefaultrunloopmode];


// Of course, this timer will be automatically started and triggered only after 10 seconds

}

Return self

}

 

 

When we click the start button,

 

-(Ibaction) starttime :( ID) sender {

// Simply call this method to see what the function is.
[_ Timer fire];

}

If the result is, click the button to reduce the countdown time by 1 and click minus 1, that is, it advances the trigger time, but after 10 seconds, the countdown will be reduced by 1, that is to say, it only triggers the timer in advance, without affecting the time set by the timer. It is like we can't wait to watch a game and drive the car faster, the fire function is like getting us to the stadium faster, but it does not affect the start time of the game.

Remember that we set yes when initializing the timer. When we change to no, we will not let it trigger cyclically. Then we will click the start button. It will suddenly find that the countdown is reduced by 1, but when we click the start button again, we will find that the countdown will not change. The reason is: our timer is set to trigger only once, and then triggered once when the fire is triggered, the timer will be automatically destroyed, and the fire will not be triggered in the future.

 

Now let's look at the official explanation, and we may understand it better,

 

 

You can use this method to fire a repeating timer without interrupting its regular Firing schedule. if the timer is non-repeating, it is automatically invalidated after firing, even if its scheduled fire date has not arrived.

That's right. Fire does not start a timer, but triggers it in advance.

Detailed usage of nstimer

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.