2015-11-07 177 views
-1

我想增強下面的代碼:當我點擊「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) 
} 

你能告訴我該怎麼做嗎?

+0

'returnUserData'確實在做這樣的循環,還是它正在做一些可能已經支持取消異步操作(例如網絡請求等)的事情? – Rob

回答

1

您可以使用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() 

這無可否認,這是一個頗爲人爲的例子,但它顯示瞭如何取消耗時的計算。

許多異步模式都有其內置的取消邏輯,無需開發子類的開銷。如果您試圖取消某些已支持取消邏輯的內容(例如NSURLSessionCLGeocoder等),則無需完成此項工作。但是如果你真的試圖取消你自己的算法,那麼NSOperation的子類就會很好地處理這個問題。