priore

Thread Safe Weak Ref Queue

May 19th, 2020
1,114
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Foundation
  2.  
  3. class WeakRef<T> where T: AnyObject {
  4.    
  5.     private let queue = DispatchQueue(label: "ThreadSafeWeakRef.queue", attributes: .concurrent)
  6.    
  7.     private(set) weak var _object: T?
  8.    
  9.     weak var object: T? {
  10.         var result: T?
  11.        
  12.         queue.sync {
  13.             result = _object
  14.         }
  15.        
  16.         return result
  17.     }
  18.    
  19.    
  20.     init(object: T?) {
  21.         queue.async(flags: .barrier) {
  22.             self._object = object
  23.         }
  24.     }
  25.    
  26. }
RAW Paste Data