我有一个函数,当我的应用程序进入后台模式时它会被调用。如果用户重新打开应用程序,我想停止线程。到目前为止,我尝试的任何方法都不起作用。
到目前为止,这是我的代码:
class Neversleep {
private static var callback : (()->Void)?
private static var thread: NSThread?
static func start(callback: ()->Void) {
self.callback = callback
Neversleep.thread = NSThread(target: self, selector: #selector(Neversleep.task), object: nil)
Neversleep.thread?.start()
}
static func stop() {
print("NEVERSLEEP:STOP")
Neversleep.thread?.cancel()
}
@objc static func task() {
while (true)
{
sleep(3);
print("we are still running!")
callback?()
}
}
}
我从应用委托(delegate)的 DidEnterBackground 方法调用 Neversleep.start()。
我正在从 willEnterForeground 调用 Neversleep.stop()...但它并没有停止线程。
我确定我在这里遗漏了一些明显的东西。但是什么?
最佳答案
在线程上调用cancel
不会自动终止线程。当线程被取消时,线程的实际主体需要停止它正在做的任何事情。
像这样更新您的任务
函数:
@objc static func task() {
while (!NSThread.currentThread.cancelled)
{
sleep(3);
print("we are still running!")
callback?()
}
}
仔细检查 currentThread
和 cancelled
的实际方法和属性名称。我不是 100% 确定它们在 Swift 2 中的名称。
即使使用上述方法,在线程因 sleep
而取消后,您仍可能会再次调用 callback
。您可以通过以下方式解决此问题:
@objc static func task() {
while (!NSThread.currentThread.cancelled)
{
sleep(3);
print("we are still running!")
if (!NSThread.currentThread.cancelled) {
callback?()
}
}
}
关于ios - 我如何停止这个 NSThread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41069729/