如何更改 DispatchQueue 中对象的延迟时间

How to change delay time for an object in DispatchQueue

我有一个 tableView,其中的单元格出现一定的延迟。延迟取决于每个单元格的文本中有多少个字母。 所以我的问题是,如果用户做某事(例如向下滚动 tableView),是否有一种方法可以更改延迟时间。

理想情况下,如果向下滚动 tableView,我希望下一个单元格毫不延迟地出现。

我想答案就在 DispatchQueue.main.async(execute: task) 的某处。虽然我不确定它是只执行下一个排队任务还是队列中的所有任务。 (显然我只需要下一个任务)。无论如何,我的应用程序下面的代码崩溃了。

var task: DispatchWorkItem?
var lastContentOffset: CGFloat = 0

//Checking if tableView was scrolled.

override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
   if lastContentOffset < scrollView.contentOffset.y {
        print("Table view scrolled-down!")
        DispatchQueue.main.async(execute: task!)
   }
   else{
        print("Scrolled up")
   }
}

//Updating my tableView with delay

func updateTableView(nextPassageID: Int) {

    task = DispatchWorkItem {
         self.numberOfCells += 1
         let indexPath = IndexPath(row: nextPassageID, section: 0)
         self.tableView.insertRows(at: [indexPath], with: .fade)
    }

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay, execute: task!)
}

如有任何帮助,我们将不胜感激。 干杯!

How to change delay time for an object in DispatchQueue

最重要的是,你没有。如果您希望它比之前预定的时间更早开始,只需 cancel 它并派遣一个没有任何延迟的新的。

或者,您可以使用 Timer, which you can schedule but also fire before the scheduled fire date occurs, it will run it and then invalidate 它。

注意强引用循环。例如,在您的闭包中(无论是 DispatchWorkItem 还是基于闭包的计时器,请考虑使用 [weak self] 捕获列表,这样闭包就不会保持对 self 的强引用。同样,如果您的 DispatchWorkItemTimer 有一个 ivar,请考虑 (a) 使用本地变量作为 item/timer,(b) 将其添加到您的 queue/runloop,然后 ( c) 让你的 ivar 成为一个 weak 引用,这样当项目是 运行 and/or 计时器触发时,你的 ivar 将自动释放,避免在它们的使用寿命之外挂起引用.