ios - 我如何停止这个 NSThread?

标签 ios swift background-process nsthread

我有一个函数,当我的应用程序进入后台模式时它会被调用。如果用户重新打开应用程序,我想停止线程。到目前为止,我尝试的任何方法都不起作用。

到目前为止,这是我的代码:

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

仔细检查 currentThreadcancelled 的实际方法和属性名称。我不是 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/

相关文章:

ios - 如何在 AVAudioPlayer 开始播放音频时准确获取通知?

android - Cordova 后台地理定位支持,应用程序不会在一段时间后终止

dependency-injection - 通过依赖注入(inject)实现后台任务的 DbContext

objective-c - 为什么 MPMoviePlayerController 没有暂停?

ios - 如何在 UICollectionView 中动态调整标题 View 的大小?

ios - 按按钮减少的计时器

ios - UIAttachmentBehavior 中的长度是如何确定的?

ios - 使用 ABPersonCopyImageData 获取 iOS 联系人图像

ios - 敲击UITextField时,加载一个nib文件以充当自定义键盘

xcode - 调试时从后台删除应用