【问题标题】:Wrap Asynchronous Function Call In an NSOperation在 NSOperation 中包装异步函数调用
【发布时间】:2015-07-11 23:12:59
【问题描述】:

我正在尝试使用带有完成处理程序的函数,调用如下:

myFunc(completion: {(var1, var2) -> Void in
    // do something interesting with variables
})

我的问题是我需要它依赖于其他 NSOperation 并且具有 NSOperation 的依赖项,因此我需要将 myFunc() 包装在 NSOperation 中。我该怎么做呢?

我已经开始研究子类化 NSOperation 并实现异步“已完成”标志,但似乎应该有一种更简单、更轻量级的方法可以在没有子类的情况下执行此操作,可能使用 NSBlockOperation 或 NSInvocationOperation。

【问题讨论】:

  • 这个问题很宽泛...所以start here如果你遇到麻烦,你可以来问一个更具体的问题。

标签: ios multithreading swift asynchronous nsoperation


【解决方案1】:

我找到了使用 AsyncOpKit 的解决方案。它允许您在内部异步调用完成后将操作标记为“完成”。这是上面定义的函数的示例代码

class MyFuncOperation: AsyncOperation {
    override main() {
        myFunc(completion: {(var1, var2) -> Void in
            // do something interesting with variables
            finish()
        })
    }
}

然后像使用任何NSOperation 子类一样使用MyFuncOperation

let operation = MyFuncOperation()
NSOperationQueue.currentQueue()!.addOperation(operation)

https://cocoapods.org/pods/AsyncOpKit

【讨论】:

    猜你喜欢
    • 2021-06-26
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多