Timer 在异步子线程 要放到 Runloop里才能使用

 let thread1 = Thread(target: self, selector: #selector(ViewController.display), object: nil)
        thread1.name = "thread1"
        thread1.start()

display 方法中 timer这么写

    func display(){
        let timer:Timer = Timer(timeInterval: 2.0,
                                target: self,
                                selector: #selector(ViewController.log),
                                userInfo: nil,
                                repeats: true)

        // 将定时器添加到运行循环
        RunLoop.current.add(timer, forMode: RunLoopMode.defaultRunLoopMode)
        RunLoop.current.run()
}

          func display(){
        Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { (timer) in
            self.log()
        }
        RunLoop.current.run()
        }

版权声明:本文为sunzhenglin2016原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。