func startTimer () { batchTimer = NSTimer.scheduledTimerWithTimeInterval(batchIntervalSeconds,target: self,selector: #selector(Requester.performRemoteRequests),userInfo: nil,repeats: false)}
事实并非如此
func startTimerInBlock () { let urlRequest = NSMutableURLRequest(URL: NSURL(string: "Google.com")!,cachePolicy: .ReloadIgnoringLocalCacheData,timeoutInterval: 30) urlRequest.httpMethod = "GET" let session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration()) let task = session.dataTaskWithRequest(urlRequest) { (data:NSData?,response:NSURLResponse?,error:NSError?) -> VoID in //check there is a response and that it is an http response self.batchTimer = NSTimer.scheduledTimerWithTimeInterval(self.batchIntervalSeconds,selector: #selector(CNVRRequester.performRemoteRequests),repeats: false) } task.resume()}
有人知道为什么在一个块内调用的计时器不会触发吗?
解决方法 简单修复,将self.startTimer代码放在dispatch_block中dispatchQueue.main.async { self.startTimer() }
那应该解决它.
编辑说明
计时器需要一个活动的运行循环.在主线程上初始化时,将自动使用主运行循环.如果要从后台线程运行它,则必须将其附加到该线程运行循环.例
dispatchQueue.global(qos: .background).async { let timer = Timer.scheduledTimer(timeInterval: 10,selector: selector(fireTimer),repeats: false) let runLoop = RunLoop.current runLoop.add(timer,forMode: .defaultRunLoopMode) runLoop.run() }
但是,如果你想确保它只是从主线程运行,只需从一个调度主关闭启动它,它将确保它将运行主线程.
编辑:已更新为Swift 3
编辑2:更新以显示背景计时器答案符合Phil Mitchells评论
总结以上是内存溢出为你收集整理的swift – 在块中调用时,NSTimer不会触发全部内容,希望文章能够帮你解决swift – 在块中调用时,NSTimer不会触发所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)