停止UIView中的所有异步任务

Ant*_*ear 2 uiview ios swift

我正在创建一个在一个UIView中运行许多异步任务的人UIViewController.在某些时候,我希望能够删除UIView并停止正在运行的所有任务.但是,呼叫removeFromSuperview()不会停止任务.有没有办法可以做到这一点?

示例代码

class ViewController: UIViewController {

    let v = SomeView()

    override func viewDidLoad() {
        super.viewDidLoad()

        v.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
        self.view.addSubview(v)

        let v1 = UIButton()
        v1.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        v1.backgroundColor = UIColor.blue
        v1.addTarget(self, action: #selector(removeV(_:)), for: .touchUpInside)
        self.view.addSubview(v1)
    }

    func removeV(_ sender: UIButton) {
        print("V REMOVED")
        v.removeFromSuperview()
    }
}

class SomeView: UIView {
    override func draw(_ rect: CGRect) {
        DispatchQueue.global().async {
            var c = 0
            while true {
                print(String(c) + " DOING SOME TASK")
                c += 1
                sleep(1)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

示例日志

0 DOING SOME TASK
1 DOING SOME TASK
V REMOVED
2 DOING SOME TASK
3 DOING SOME TASK
4 DOING SOME TASK
...
Run Code Online (Sandbox Code Playgroud)

jar*_*ora 5

有一种方法可以使用DispatchWorkItem取消DispatchQueue中的块.例如.

//create the dispatch work item
var dwi2:DispatchWorkItem?
dwi2 = DispatchWorkItem {
    var c = 0
    while true {
        print(String(c) + " DOING SOME TASK")
        c += 1
        sleep(1)
        if (dwi2?.isCancelled)!{
            break
        }
    }
}

//submit the work item to the default global queue
DispatchQueue.global().async(execute: dwi2!)

//cancelling the task after 3 seconds
DispatchQueue.global().async{
    sleep(3)
    dwi2?.cancel()
}
Run Code Online (Sandbox Code Playgroud)

您必须检查工作块中的isCancelled属性以停止进一步执行.

有关详细信息,请参阅书写的好文章.