IOS --- precautions for using NSTimer to set scheduled tasks
NSTimer is a timer mechanism in iOS development. It is often used to set scheduled tasks using its ischeduledTimerWithTimeInterval method.
We will use a countdown timer to illustrate the following points of attention.
Set timer
Click the button to add a countdown timer:
func demoNSTimer() { btn.userInteractionEnabled = !btn.userInteractionEnabled countdown = countTimer if (timer != nil) { timer.invalidate() timer = nil } timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: actionNSTimer, userInfo: nil, repeats: true) timer.fire()}
Timer trigger:
func actionNSTimer() { if (countdown < 1) { if (timer != nil) { countdown = countTimer timer.invalidate() timer = nil lb.text = (countdown) lb.alpha = 1.0 } return; } lb.text = (countdown) lb.transform = CGAffineTransformMakeScale(1.0, 1.0) lb.alpha = 1.0 countdown = countdown - 1 UIView.animateWithDuration(1.0, animations: { () -> Void in self.lb.transform = CGAffineTransformMakeScale(2.0, 2.0) self.lb.alpha = 0.0 }) { (Bool) -> Void in if (self.countdown == 0) { self.btn.userInteractionEnabled = true } }}
With the above code, you can create a countdown timer.
Pause and resume Timer
When the timer is being executed, the invalidate method cannot be used to pause, but the fireDate method must be reset.
If (timer. valid) {timer. fireDate = NSDate. distantFuture () // pause // timer. fireData = NSDate. distantPast () // restore}
For example, if the APP enters the background (press the Home Key), you usually need to pause the timer. You can use NSNotification in applicationWillResignActive to pause the timer, and then notify the recovery timer in applicationDidBecomeActive.
RunLoop Mode
Nstablecannot be placed in UITableView or UIScrollView, because cell reuse will invalidate it. It is actually the reason for Runloop Mode.
// Modify the mode. In this way, the message of other runloop can be received during the rolling process. The message is. nlunloop. currentRunLoop (). addTimer (timer, forMode: nsunloopcommonmodes)
When NSURLConnection is used for initWithRequest, the same asynchronous request thread as NSTimer is created for NSDefaultRunLoopMode.
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)connection.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)connection.start()