美文网首页iOS
(Weak Singleton)弱单例优化

(Weak Singleton)弱单例优化

作者: CNKCQ | 来源:发表于2019-09-26 16:18 被阅读0次

(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

相关文章

网友评论

    本文标题:(Weak Singleton)弱单例优化

    本文链接:https://www.haomeiwen.com/subject/yrknuctx.html