-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)
}

你能告诉我怎么做吗?

4

1 回答 1

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()

诚然,这是一个相当人为的示例,但它显示了如何取消耗时的计算。

许多异步模式都有其内置的取消逻辑,从而消除了对子NSOperation类开销的需求。如果您尝试取消已经支持取消逻辑的某些内容(例如NSURLSessionCLGeocoder等),则不必完成这项工作。但是如果你真的想取消你自己的算法,NSOperation子类会非常优雅地处理这个问题。

于 2015-11-07T01:26:24.230 回答