swift3.0下的NSTimer和GCD

基于其他高级语言(如java),swift3.0对OC中的许多类名进行了省略,如CGFloat变成Float,NSURL变成了URL,NSURLRequest变成URLRequest,NSTimer变成了Timer,dipatch_time_t变成DispatchQueue......如此的调整,个人推测是为了增加Swift的应用范围(传言的swift开发有机会晋升为全栈工程师也并非没有可能).前途是光明的,道路的曲折却需要填很多坑.下面记录一下工程在向Swift3.0迁移的过程中,遇到的NSTimer和GCD应用的问题
1Timer的启用和暂停
在UIView的子类,如UITableViewCell中,可以用懒加载的方式创建Timer:

lazy var timer: Timer = Timer.scheduledTimer(timeInterval: homeRefreshInterval, target: self, selector: #selector(timerFire), userInfo: nil, repeats: true)

启用和暂停如下:

//启用
cellTimer?.fireDate = NSDate.distantPast
//暂停
cellTimer?.fireDate = NSDate.distantFuture

而在UIViewController的子类中,用懒加载的方式创建Timer时,会导致通不过编译(推测原因需要保证在主线程创建View页面完成后,才可以使用Timer).一般实现方式如下:

var timer: Timer?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.timer = Timer.scheduledTimer(timeInterval: refreshTimeInterval, target: self, selector: #selector(loadData), userInfo: nil, repeats: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        timer?.fireDate = NSDate.distantPast
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        timer?.fireDate = NSDate.distantFuture
    }

2GCD实现延迟

//延迟后在主线程刷新UI
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
                self.aIV.stopAnimating()
                self.navigationItem.rightBarButtonItem = self.refreshImage
            }

在stackOverFlow中看到的使用方式如下:

    var mDispatchQuquq: DispatchQueue?
    var mDispatchWorkItem: DispatchWorkItem?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.mDispatchQuquq = DispatchQueue.global(qos: .background)// create Dispatch queue
        self.mDispatchWorkItem = DispatchWorkItem {//ceate dispatch item
            // TO DO... asinc code
            print("uptimeNanoseconds")
        }
        if self.mDispatchWorkItem != nil {
            // launcher .asyncAfter
            self.mDispatchQuquq?.asyncAfter(deadline:  .now() + .seconds(3),
                                            execute: self.mDispatchWorkItem!)
        }
    }

swift3.0对类名的变化的同时,伴随着使用方式的改变,使用的过程中免不了看官方文档,查看StackOverFlow等论坛.相信以后问题还有很多,但同时也意味着解决问题之后的进步,加油!

你可能感兴趣的:(swift3.0下的NSTimer和GCD)