Use of Nstimer

Source: Internet
Author: User

Nstimer actually is to add a listener to the system's Runloop, when the system Runloop to how the timer condition loop, will call the timer once, when the timer executes, That is, after the callback function is executed, thetimer will once again add itself to the Runloop to continue listening.

Define a timer:

Nstimer *timer=[nstimer scheduledtimerwithtimeinterval:0.1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];

Common methods:

[Timer fire];// can fire this method to trigger the timer, let it execute immediately, even if the timer's firing time does not arrive

[Timer invalidate]; Stops and removes the method that moves the timer out of the Runloop. Generally controlled by runloop, do not need to set their own

[Timer setfiredate:[nsdate distantfunture]];//pause execution

[Timer setfiredate:[nsdate date]];//Continue execution

[Timer setfiredate:[nsdate distantpast]];//Open

What is the difference between the open method and the continuation method?

@interfaceNstimer:nsobject//initialize, preferably in scheduled mode, or manual addtimer:formode: Add a timer to a runloop. + (Nstimer *) Timerwithtimeinterval: (nstimeinterval) ti invocation: (nsinvocation *) invocation repeats: (BOOL) Yesorno;+ (Nstimer *) Scheduledtimerwithtimeinterval: (nstimeinterval) ti invocation: (nsinvocation *) invocation repeats: (BOOL) Yesorno;+ (Nstimer *) Timerwithtimeinterval: (nstimeinterval) ti target: (ID) Atarget selector: (SEL) aselector UserInfo: (ID) UserInfo repeats: (BOOL) Yesorno;+ (Nstimer *) Scheduledtimerwithtimeinterval: (nstimeinterval) ti target: (ID) Atarget selector: (SEL) aselector UserInfo: (ID) UserInfo repeats: (BOOL) Yesorno;- (ID) Initwithfiredate: (nsdate *) date interval: (nstimeinterval) ti target: (ID) T selector: (SEL) s UserInfo: (ID) UI repeats: (BOOL) rep;- (void) Fire;//Trigger Timer immediately-(NSDate *) firedate;//Start Time- (void) Setfiredate: (NSDate *) date;//set Firedata, actually pause, start will use-(Nstimeinterval) timeinterval;//Delay Time- (void) invalidate;//Stop and delete-(BOOL) isValid;//Judging whether valid- (ID) UserInfo;//usually with nil@end

Before invalidate, it is better to use IsValid first to determine whether or not in the thread:

if ([scrolltimer isValid] = = YES) {        [scrolltimer invalidate];        Scrolltimer = nil;}

Nstimer invalidate after IsValid program crashes
When using Nstimer, if I call invalidate and then use IsValid to determine the state of the current timer, an invalid memory reference will occur and the program crashes. The reason is that Nstimer is an automatically released object, when the call to invalidate will automatically release the object, so call IsValid again when you will be prompted to reference invalid address. The solution is to set the timer to nil after each call to invalidate, and then determine whether the timer is nil on the call to IsValid. Benzene method, but solve my needs!
Self.m_timertimeout = [Nstimer scheduledtimerwithtimeinterval:1.0  target:self                                                      selector: @selector ( handletimeoutaction) Userinfo:nil Repeats:yes];

The first parameter, 1.0 for 1 seconds, defaults to 0.1 if the value is <0
The second parameter, Target: (ID) Atarget, represents the sent object, such as self
The third parameter, selector: (SEL) Aselector method Selector, within the time interval, select to invoke an instance method
The fourth parameter, UserInfo: (ID) userInfo This parameter can be nil, and when the timer expires, the timer is reserved and freed by the object you specify.
The fifth parameter, repeats: (BOOL) Yesorno When Yes, the timer will continue to loop until it expires or is released, and when no, the timer will be sent to the loop once to fail.

iphone Nstimer invalidate and release issues
Recently in the use of Nstimer, encountered some memory errors in the problem, found a good article unfortunately is English, is now translated out for later use.
Original:
[Timer release] only needs to being called if you "own" the timer. From Apple ' s documentation:
Because The run loop maintains the timer, from the perspective of memory management there ' s typically no need to keep a re Ference to a timer once you ' ve scheduled it. Since the timer is passed as a argument if you specify it method as a selector, you can invalidate a repeating timer W Hen appropriate within that method. In many situations, however, you also want the option of invalidating the timer-perhaps even before it starts. In this case, you did need to keep a reference to the timer, so, can send it an invalidate message whenever is APPR Opriate. If you create an unscheduled timer (see "Unscheduled timers") and then you must maintain a strong reference to the timer (in A reference-counted environment, you retain it) so that it's not deallocated before your use it.
What does this mean?
If You alloc and init a timer, you must also release it, like so:
Nstimer * timer = [[Nstimer alloc] initwith ...];
Nsrunloop * Runloop = [Nsrunloop currentrunloop];

[Runloop Addtimer:timer Formode:nsdefaultrunloopmode];

[Timer release];
......
[Timer invalidate];

Timer = nil;

Once the timer had been added to the run loop, there was no reason to keep a reference to it anymore, since the run loops O Wns it. In this case, as shown, would release of the timer as soon as you add it to the run loop, and then simplyinvalidate it wh En you is finished. The final line, setting timer to nil, is for safety. The call to invalidate would result in the timer being released (by the run loop), so it's unsafe to keep a reference that Points to it. Setting the local reference to nil keeps things kosher.
If, however, you create a timer using one of the convenience methods like so:
Nstimer * timer = [Nstimer scheduledtimerwithtimeinterval ...];

Need to call [timer release] at all!

The convenience method adds the timer to the run loop, which and then owns it, so don't need to perform any memory manage ment on the returned timer object. You would simplyinvalidate the timer when you are no longer want to use it:
[Timer invalidate];timer = nil;

Or, if the timer is not set to repeat, you would does absolutely nothing @ all, since it would is released after its first Invocation.

[Timer release] This method can only be called when you have a timer. According to Apple's documentation, it is described as follows: Because Runloop keeps the timer. From the memory management point of view, when we scheduled (scheduled) a timer, we usually do not need to maintain its reference (reference count). Since the timer is passed as a parameter, the timer's specified method is in the form of selector, so you can invalidate a repeating timer (repeating timer) within the specified method, at the appropriate time. However, in many situations, you may want to invalidating a timer before the timer starts. In this case, you must keep a reference to the timer (reference) so that you can send the invalidate message to the timer at the appropriate time. If you create a unscheduled timer, you must keep a strong reference for this timer (in the context of Reference_count (reference counting), you send a retain message to the timer), n this is done to ensure that it will not be deallocated until you use the timer. In short: If you allloc init a timer, you must release it, for example:
Nstimer * timer = [[Nstimer alloc] initwith ...];
Nsrunloop * Runloop = [Nsrunloop currentrunloop];
[Runloop Addtimer:timer Formode:nsdefaultrunloopmode];
[Timer release];
......
[Timer invalidate];
Timer = nil;
Once the timer is added to the runloop, we have no reason to keep a reference because Runloop will keep it. In this show, as we have shown, you should release it, when you add it to the Runloop, and invalidate at the end of the timer as in the example. The last line of code (Timer = nil) is for security. Invalidate calls will cause the timer to be release (controlled by Runloop), so it is unsafe to keep a reference to the timer. Setting the local reference to null is a rule-compliant.
Anyway, if you create a timer follow this form:
Nstimer * timer = [Nstimer scheduledtimerwithtimeinterval ...];
You don't need to call [timer release]!
This handy way to add a timer to the Runloop,runloop will keep the timer's reference count, so you don't need to implement any of the objects on the returned timer object.
Memory management. You should want to invalidate the timer as in the example, as follows:
[Timer invalidate];timer = nil;
Or, if the timer is not set to repeat (repeat), you are relieved that you do not need to do anything because he will release the timer after the first call is complete.

Transfer from http://www.cnblogs.com/ios-wmm/archive/2012/08/24/2654779.html

Use 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.