dispatch_once after the Swift 3 GCD API changes

后端 未结 9 1721
忘掉有多难
忘掉有多难 2020-11-28 20:48

What is the new syntax for dispatch_once in Swift after the changes made in language version 3? The old version was as follows.

var token: dispa         


        
9条回答
  •  鱼传尺愫
    2020-11-28 21:15

    Swift 3: For those who likes reusable classes (or structures):

    public final class /* struct */ DispatchOnce {
       private var lock: OSSpinLock = OS_SPINLOCK_INIT
       private var isInitialized = false
       public /* mutating */ func perform(block: (Void) -> Void) {
          OSSpinLockLock(&lock)
          if !isInitialized {
             block()
             isInitialized = true
          }
          OSSpinLockUnlock(&lock)
       }
    }
    

    Usage:

    class MyViewController: UIViewController {
    
       private let /* var */ setUpOnce = DispatchOnce()
    
       override func viewWillAppear() {
          super.viewWillAppear()
          setUpOnce.perform {
             // Do some work here
             // ...
          }
       }
    
    }
    

    Update (28 April 2017): OSSpinLock replaced with os_unfair_lock due deprecation warnings in macOS SDK 10.12.

    public final class /* struct */ DispatchOnce {
       private var lock = os_unfair_lock()
       private var isInitialized = false
       public /* mutating */ func perform(block: (Void) -> Void) {
          os_unfair_lock_lock(&lock)
          if !isInitialized {
             block()
             isInitialized = true
          }
          os_unfair_lock_unlock(&lock)
       }
    }
    

提交回复
热议问题