(Weak Singleton)弱单例优化

单例的的销毁与重建

static MusesEditLog *instance = nil;
static dispatch_once_t onceToken;

+ (instancetype)shared {
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc] init];
    });
    return instance;
}

+ (void)dispose {
    instance = nil;
    onceToken = 0l;
}

(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)弱单例优化)