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()
確かに、これはかなり不自然な例ですが、時間のかかる計算をキャンセルする方法を示しています。
NSOperation
多くの非同期パターンにはキャンセル ロジックが組み込まれているため、サブクラスのオーバーヘッドが不要になります。既にキャンセル ロジックをサポートしているもの ( 、 など) をキャンセルしようとしている場合はNSURLSession
、CLGeocoder
この作業を行う必要はありません。しかし、実際に独自のアルゴリズムをキャンセルしようとしている場合は、NSOperation
サブクラスがこれを非常に適切に処理します。