【问题标题】:On which thread is a Swift property's didSet{} being executed?Swift 属性的 didSet{} 在哪个线程上执行?
【发布时间】:2015-12-02 09:36:24
【问题描述】:

我在 Swift 中定义了一个属性,例如:

var foo : String {
  didSet {
    doSomething()
  }
}

所以每次我将foo 设置为foo = "bar" 我的didSet 都会被执行。

但是我找不到在哪个线程上didSet正在执行。

例如在这种情况下会发生什么:

dispatch_async(some_queue, { () -> Void in
     self.foo = "bar"
})

这将导致didSet 代码被执行。 didSet 会在 some_queue 上运行还是始终在 main_queue 上运行?

【问题讨论】:

  • 您可以在didSet 中使用NSThread.isMainThread() 来找出程序在那里运行的线程。如果您使用dispatch_async(some_queue.... 设置该属性,则必须在some_queue 上调用它
  • 我知道如何强制排队。我只是想知道默认行为。

标签: multithreading swift closures


【解决方案1】:

属性观察者willSetdidSet直接在setter方法中被立即调用 在存储新值之前/之后,所有这些都在同一个线程上执行。

您可以通过在didSet 中设置断点并检查 堆栈回溯,如下所示:

* 线程 #2:tid = 0x4df3, 0x000000010024f9eb swtest2`swtest2.foo.didset : Swift.String(oldValue="foo") + 27 at main.swift:6, queue = 'myQueue', stop reason = breakpoint 1.1 * 帧 #0: 0x000000010024f9eb swtest2`swtest2.foo.didset : Swift.String(oldValue="foo") + 27 at main.swift:6 帧#1:0x000000010024fb91 swtest2`swtest2.foo.setter:Swift.String(newValue="bar") + 177 at main.swift:4 帧 #2: 0x000000010024fe3a swtest2`swtest2.(closure #1) + 42 at main.swift:13 ...

【讨论】:

  • 实际上是有趣的信息。我一直在考虑使用 NSThread 类来了解多线程在 iOS 中的行为方式。你知道如何使用这样的类来达到同样的效果吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 2016-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多