iOS --- 使用NSTimer设置定时任务的注意事项
2015-10-11 14:43
585 查看
NSTimer是iOS开发中的定时器机制,常用其ischeduledTimerWithTimeInterval方法来设置定时任务。
我们以一个倒计时的定时器来说明下边几点要注意的事项。
定时器触发:
通过以上代码,可创建一个倒计时的定时器。
例如:如果APP进入后台(按下Home键),则一般情况下需要暂停定时器。可在applicationWillResignActive中使用NSNotification来暂停定时器,在applicationDidBecomeActive中再通知恢复定时器。
使用NSURLConnection的initWithRequest的时候, 创建异步请求线程和NSTimer一样,也是NSDefaultRunLoopMode的.
我们以一个倒计时的定时器来说明下边几点要注意的事项。
设置定时器
点击按钮,添加一个倒计时的定时器: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() }
定时器触发:
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 } } }
通过以上代码,可创建一个倒计时的定时器。
暂停和恢复定时器
当定时器正在执行的过程中,暂停是不能使用invalidate方法的,而要重新设置fireDate。if (timer.valid) { timer.fireDate = NSDate.distantFuture() // 暂停 // timer.fireData = NSDate.distantPast() // 恢复 }
例如:如果APP进入后台(按下Home键),则一般情况下需要暂停定时器。可在applicationWillResignActive中使用NSNotification来暂停定时器,在applicationDidBecomeActive中再通知恢复定时器。
RunLoop模式
NSTimer不能放在UITableView或UIScrollView中, 因为cell的reuse会使其失效. 其实是Runloop Mode的原因.// 修改mode, 这样滚动的时候也可接收其他runloop的消息了. NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
使用NSURLConnection的initWithRequest的时候, 创建异步请求线程和NSTimer一样,也是NSDefaultRunLoopMode的.
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false) connection.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes) connection.start()
Demo
Demo地址: DemoNSTimer相关文章推荐
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 不可修补的 iOS 漏洞可能导致 iPhone 4s 到 iPhone X 永久越狱
- iOS 12.4 系统遭黑客破解,漏洞危及数百万用户
- 每日安全资讯:NSO,一家专业入侵 iPhone 的神秘公司
- [转][源代码]Comex公布JailbreakMe 3.0源代码
- js判断客户端是iOS还是Android等移动终端的方法
- IOS开发环境windows化攻略
- .net平台推送ios消息的实现方法
- 使用 Iisftp.vbs 暂停FTP站点的方法
- 探讨Android与iOS,我们将何去何从?
- Android、iOS和Windows Phone中的推送技术详解
- jQuery及JS实现循环中暂停的方法
- IOS 改变键盘颜色代码
- 举例详解iOS开发过程中的沙盒机制与文件
- Android和IOS的浏览器中检测是否安装某个客户端的方法
- javascript实现阻止iOS APP中的链接打开Safari浏览器
- IOS开发第三方语音-微信语音
- iOS开发之路--微博OAuth授权_取得用户授权的accessToken