如何使用 Swift 检查线程是否正在运行或完成

3

我真的不知道如何在swift中检查线程是否存活。

在我的情况下,在按钮点击事件中,我正在创建一个新线程并开始一个NSTimer对象。在规律的时间间隔内,我需要检查线程是否存活。

那么我该如何检查线程是否存活呢?

var objDS= DeviceStatus()
let thread = NSThread(target: objDS, selector: "checkDeviceStatus", object: nil)

如果可能的话,请提供一个示例或一些参考链接。
谢谢,

你是如何创建线程的?你能添加相关代码吗? - Midhun MP
1个回答

5
你可以通过线程的执行状态属性来确定它。 执行中
var executing: Bool { get } // true if the receiver is executing, otherwise false.

已完成

var finished: Bool { get } //true if the receiver has finished execution, otherwise false.

取消

var cancelled: Bool { get } //true if the receiver has been cancelled, otherwise false.

例子:

var objDS= DeviceStatus()
let thread: NSThread = NSThread(target: objDS, selector: "checkDeviceStatus", object: nil)

if thread.executing{
    println("executing")
}

if thread.finished{
    println("finished")
}

if thread.cancelled{
    println("cancelled")
}

有一点需要注意,声明时确保指定类型,例如:“let thread: NSThread = NSThread(...)” - Shamsudheen TK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接