iOS

(Weak Singleton)弱单例优化

2019-09-26  本文已影响0人  CNKCQ

(Weak Singleton)弱单例优化

在 OC 中

+ (instancetype)shared
{
    static __weak ACGUtility *instance;
    ACGUtility *strongInstance = instance;
    @synchronized(self) {
        if (strongInstance == nil) {
            strongInstance = [[[self class] alloc] init];
            instance = strongInstance;
        }
    }
    return strongInstance;
}

在 swift 中

    static weak var weakInstance: ACGUtility?
    static var sharedInstance: ACGUtility {
        get {
              if let instance = weakInstance {
                    return instance
              } else {
                    let newInstance = ACGUtility()
                    weakInstance = newInstance
                    return newInstance
                    }
            }  
    }

优化前:


image.png

优化后:


image.png
上一篇 下一篇

猜你喜欢

热点阅读