Ios 可取消的后台任务:NSOperation、GCD或NSThread?
我是斯威夫特的新手,不知道该怎么做 当点击一个按钮时,我需要启动一个后台任务来做一些操作,当再次点击同一个按钮时,我需要停止这个任务 我不确定是使用Ios 可取消的后台任务:NSOperation、GCD或NSThread?,ios,iphone,multithreading,swift,Ios,Iphone,Multithreading,Swift,我是斯威夫特的新手,不知道该怎么做 当点击一个按钮时,我需要启动一个后台任务来做一些操作,当再次点击同一个按钮时,我需要停止这个任务 我不确定是使用NSOperation、GCD还是NSThread 有人能给我举个简单的例子吗?既然您想轻松取消正在运行的任务,我建议您使用NSOperation。GCD不提供取消执行块的内置方法,使用NSThread通常是过分的 下面是一个简单的工作示例。它在视图控制器内创建一个按钮。点击它时,将创建一个新的NSBlockOperation,并将其添加到NSOpe
NSOperation
、GCD还是NSThread
有人能给我举个简单的例子吗?既然您想轻松取消正在运行的任务,我建议您使用
NSOperation
。GCD不提供取消执行块的内置方法,使用NSThread
通常是过分的
下面是一个简单的工作示例。它在视图控制器内创建一个按钮。点击它时,将创建一个新的NSBlockOperation
,并将其添加到NSOperationQueue
。再次点击时,队列中的所有操作都将取消
import Foundation
import UIKit
class ViewController: UIViewController {
// Create the queue to run our operation
let queue = NSOperationQueue()
override func viewDidLoad() {
super.viewDidLoad()
// Create the button
let button = UIButton.buttonWithType(.System) as! UIButton
button.setTranslatesAutoresizingMaskIntoConstraints(false)
button.setTitle("Tap me!", forState: .Normal)
button.addTarget(self, action: "buttonTapped",
forControlEvents: .TouchUpInside)
view.addSubview(button)
// Layout the button
let views: [NSObject: AnyObject] = ["button": button]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-[button]-|", options: nil, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-20-[button(44)]", options: nil, metrics: nil, views: views))
}
func buttonTapped() {
if queue.operationCount == 0 {
// Create a new operation
let operation = NSBlockOperation()
operation.addExecutionBlock { [weak operation] in
while operation?.cancelled == false {
// Do something interesting as long as
// the operation was not canceled
println("do stuff")
sleep(1)
}
println("stop doing stuff")
}
// Add the operation to the queue (this will also
// start the operation)
queue.addOperation(operation)
} else {
// Cancel all operations in the queue
queue.cancelAllOperations()
// An alternative could be to keep a reference
// to the single operation and cancel that one
// instead. The effect is the same in this simple
// example.
}
}
}
当您在模拟器中运行上述代码段时,您将能够在控制台上观察输出。是否需要重复该操作,直到第二个按钮单击为止?还是仅仅是一个方法调用?你想做什么样的手术。请发布您可能尝试过的任何代码。@Roman Sausarnes-无需重复该操作。例如,谢谢,我将尝试更新。谢谢。。对于示例代码。