iOS 开发~项目常用,经典内容收集一口海之言iOS Foundations

iOS-singleton(单例)三种创建方式

2017-08-21  本文已影响319人  iOS开发周立贺

单例介绍

单例写法

#import "SingletonVC.h"

// 创建静态对象 防止外部访问
static SingletonVC * _singletonVC;

@implementation SingletonVC

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    
    static dispatch_once_t onceToken;
    // 一次函数
    dispatch_once(&onceToken, ^{
        if (_singletonVC == nil) {
            _singletonVC = [super allocWithZone:zone];
        }
    });
    
    return _singletonVC;
}

+ (instancetype)share{
    
    return  [[self alloc] init];
}

@end
#import "SingletonVC.h"

// 创建静态对象 防止外部访问
static SingletonVC * _singletonVC;

@implementation SingletonVC

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    
    //线程锁
    @synchronized (self) {
        if (_singletonVC == nil) {
            
            _singletonVC = [super allocWithZone:zone];
        }
    }
    
    return _singletonVC;
}

+ (instancetype)share{
    
    return  [[self alloc] init];
}

@end

#import "SingletonVC.h"

static SingletonVC * _singletonVC;

@implementation SingletonVC

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    
    if (_singletonVC == nil) {
        _singletonVC = [super allocWithZone:zone];
    }
    return _singletonVC;
}

+ (instancetype)share{
    
    return  [[self alloc] init];
}

@end
上一篇下一篇

猜你喜欢

热点阅读