Swift 单例 线程安全

public struct UserCache {
    
    // 用户标识
    private var _userCode: String?
    
    // 递归锁
    private static var lock = NSRecursiveLock();
    
    private static var userCache: UserCache = UserCache()
    
    static func sharedManager() -> UserCache {
        return userCache;
    }
    
    init() {
        // 获取本地缓存
        // userCode = ...
    }
    
    var userCode: String? {
        set {
            Self.lock.lock();
            defer { Self.lock.unlock() }
            
            _userCode = newValue
        }
        get {
            _userCode
        }
    };
    
}
posted @ 2024-08-08 23:22  IT_IOS_MAN  阅读(12)  评论(0编辑  收藏  举报