swift - 如何在 0.3 秒后执行给定次数的 Action ?

标签 swift grand-central-dispatch core-foundation

let expecation = expectationWithDescription("do tasks")
for i in 0...40 {

    let afterTiming = 0.3 * Double(i)
    let startTime = CFAbsoluteTimeGetCurrent()

    let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(afterTiming * Double(NSEC_PER_SEC)))

    dispatch_after(delayTime, dispatch_get_main_queue()) {
        let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
        print("\(afterTiming) - \(timeElapsed) : \(i)")
    }
}

waitForExpectationWithTimeout(14)

在 30 执行后将近一秒,控制台开始表现怪异,同时显示两条和两条打印线

9.0 - 9.88806998729706 : 30
9.3 - 9.88832598924637 : 31

XCTest 是否有任何方法可以更接近于“在正确的时间”实际执行请求?就像得到应该在 9 秒后完成的请求在 9.88 秒后没有完成..

最佳答案

不确定您是否准备使用分派(dispatch),但 NSTimer 在我的测试中表现得更加准确。下面是一些示例代码,用于运行一个 Action numOfTimes 次

var iterationNumber = 0
var startTime = CFAbsoluteTimeGetCurrent()
let numOfTimes = 30

// Start a repeating timer that calls 'action' every 0.3 seconds 
var timer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)

func action() {
    // Print relevant information
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    print("\(Double(iterationNumber+1) * 0.3) - \(timeElapsed) : \(CFAbsoluteTimeGetCurrent())")

    // Increment iteration number and check if we've hit the limit
    iterationNumber += 1
    if iterationNumber > numOfTimes {
        timer.invalidate()
    }
}

程序的一些输出:

7.8 - 7.80285203456879 : 25
8.1 - 8.10285001993179 : 26
8.4 - 8.40283703804016 : 27
8.7 - 8.70284104347229 : 28
9.0 - 9.00275802612305 : 29
9.3 - 9.3028250336647 : 30

它保持在预期时间的几毫秒内(我假设这是调用 CFAbsoluteTimeGetCurrent 所需的时间)并且不会漂移或将它们聚集在一起。

这种方法的一个缺点是它不会像在您的代码中那样预先安排每个操作,尽管我不确定这对您是否重要。

关于swift - 如何在 0.3 秒后执行给定次数的 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36693913/

相关文章:

ios - SwiftUI .onTapGesture 从未调用过

ios - 如果响应返回 200 以外的状态代码,是否停止我的 NSURLSession?在环球银行金融电信协会

objective-c - 双模 ARC/GC 和 Core Foundation 桥接

xcode - 确定在 Swift 中创建对称 key 异常的原因

ios - 快速将按钮操作添加到 TableView 单元格

ios - 当我在 xcode 上从 iPad 切换到 iPhone "view as"时,一个场景看起来仍然像 iPad

ios - GCD设置线程间的调度/优先级

c++ - 检索当前/自己的包的路径

swift - Swift 将图像添加到 UICollection header

ios - Swift iOS -UrlSession 移动非常慢。有没有办法同时执行多个任务?