LoginSignup
2
1

More than 5 years have passed since last update.

DispatchQueueは強参照を保持しない

Posted at

コード (Playground)

import Cocoa
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

weak var workItem: DispatchWorkItem?
if true {
    let item = DispatchWorkItem() { Swift.print("delayed job") }
    DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: item)
    workItem = item
}
Swift.debugPrint(workItem as Any)

結果

nil
delayed job

対策

DispatchWorkItemを強参照で保持する。
または、ブロックを使用する。

DispatchQueue.main.asyncAfter(deadline: .now() + 1) { Swift.print("delayed job") }
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1