gpt4 book ai didi

swift - 如何阻止线程在 Swift 中无限期运行?

转载 作者:行者123 更新时间:2023-11-28 08:25:27 24 4
gpt4 key购买 nike

我从一个我看不到实现的库中运行一个函数。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
someClass.beginService();
});

这个库类调用我类的委托(delegate)函数。

class Mine: UIViewController, SomeClassDelegate {

let someClass = SomeClass();

override func viewDidLoad () {
super.viewDidLoad();
someClass.delegate = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
self.someClass.beginService();
});
}

func delegateCall () {
print ("delegateCall is called!");
// do some stuff
}
}

单词delegateCall is called!然后在日志窗口中每 1 秒定期打印一次,因为我调用了 self.someClass.beginService(); .

问题是,我怎样才能终止这个线程?我不想求助于:

class Mine: UIViewController, SomeClassDelegate {

let someClass = SomeClass();
var okToRun = false;

override func viewDidLoad () {
super.viewDidLoad();
someClass.delegate = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
self.someClass.beginService();
okToRun = true;
});
}

func delegateCall () {
if okToRun {
print ("delegateCall is called!");
// do some stuff
}
}

@IBAction func buttonStopTapped (sender: AnyObject) {
okToRun = false;
}
}

因为这意味着后台例程仍在工作。

最佳答案

尝试使函数失效。喜欢

var  thread = dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
self.someClass.beginService();

你想停在哪里

thread.invalidate()

关于swift - 如何阻止线程在 Swift 中无限期运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40169938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com