如何取消完成处理程序?
问题描述:
我想增强下面的代码:当我点击“submitData”按钮时,添加的代码应该取消完成处理程序。如何取消完成处理程序?
func returnUserData(completion:(result:String)->Void){
for index in 1...10000 {
print("\(index) times 5 is \(index * 5)")
}
completion(result: "END");
}
func test(){
self.returnUserData({(result)->() in
print("OK")
})
}
@IBAction func submintData(sender: AnyObject) {
self.performSegueWithIdentifier("TestView", sender: self)
}
你能告诉我该怎么做吗?
答
您可以使用NSOperation
这个子类。把你的计算放在main
方法里面,但是要定期检查cancelled
,如果是的话,跳出计算。
例如:
class TimeConsumingOperation : NSOperation {
var completion: (String) ->()
init(completion: (String) ->()) {
self.completion = completion
super.init()
}
override func main() {
for index in 1...100_000 {
print("\(index) times 5 is \(index * 5)")
if cancelled { break }
}
if cancelled {
completion("cancelled")
} else {
completion("finished successfully")
}
}
}
然后你就可以操作添加到操作队列:
let queue = NSOperationQueue()
let operation = TimeConsumingOperation { (result) ->() in
print(result)
}
queue.addOperation(operation)
而且,你可以取消,只要你想要的:
operation.cancel()
这无可否认,这是一个颇为人为的例子,但它显示了如何取消耗时的计算。
许多异步模式都有其内置的取消逻辑,无需开发子类的开销。如果您试图取消某些已支持取消逻辑的内容(例如NSURLSession
,CLGeocoder
等),则无需完成此项工作。但是如果你真的试图取消你自己的算法,那么NSOperation
的子类就会很好地处理这个问题。
'returnUserData'确实在做这样的循环,还是它正在做一些可能已经支持取消异步操作(例如网络请求等)的事情? – Rob