【问题标题】:How can you stop/cancel callback in Swift3?如何在 Swift3 中停止/取消回调?
【发布时间】:2017-11-04 05:50:16
【问题描述】:

在我的应用程序中,我有一个进行云调用的方法。它有一个完成处理程序。在某些时候,当用户向云进行此调用并且在等待完成时,用户可能会点击注销。

这将从堆栈中删除控制器,因此完成块将返回到不再在堆栈上的控制器。

这会导致崩溃,因为我在完成返回时执行了一些 UI 任务。 我做了一个解决方法,我没有对 UI 做任何事情是控制器不再在堆栈上。

但是,我很好奇是否可以在注销时以某种方式取消/停止所有挂起的回调?

【问题讨论】:

  • 如果您在完成块中使用对 self 的弱引用,您应该能够避免任何保留/nil 问题并在 VC 被取消初始化的情况下停止块运行

标签: ios swift callback completionhandler


【解决方案1】:

为了对操作的取消进行精细控制,您可以从函数中返回一个取消令牌。在需要取消操作时调用它。

这是一个如何实现的示例:

typealias CancellationToken = () -> Void

func performWithDelay(callback: @escaping () -> Void) -> CancellationToken {
    var cancelled = false
    // For the sake of example delayed async execution 
    // used to emulate callback behavior.
    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
        if !cancelled {
            callback()
        }
    }
    return { cancelled = true }
}

let cancellationToken = performWithDelay {
    print("test")
}

cancellationToken()

如果您只需要确保在块执行中仍然满足所有必要的先决条件和条件,您可以使用guard

  { [weak self] in 
    guard let `self` = self else { return }
    // Your code here... You can write a code down there 
    // without worrying about unwrapping self or 
    // creating retain cycles.
  }

【讨论】:

    【解决方案2】:

    我不确定,但我认为某些东西是紧密耦合的。尝试做:

    { [weak self] () -> Void in
                guard let _ = self else { return }
    //rest of your code
    }
    

    如果您被取消初始化,那么您的 completioHanlder 将不会继续。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      相关资源
      最近更新 更多