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()
        }

你可能感兴趣的:(oc,swift)