iOS单例的几种写法

单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。

一、只用于单线程(多线程不安全)

static Share *_instance = nil;

@implementation Share
//线程不安全
+ (instancetype)shared {
    return [[self alloc] init];
}

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

- (id)copyWithZone:(NSZone *)zone {
    return _instance;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return _instance;
}

@end

二、使用dispatch_once只创建一次 (推荐)

static Share *_instance = nil;

@implementation Share

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

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t oneceToken;
    dispatch_once(&oneceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

//为了严谨重写copy mutableCopy
- (id)copyWithZone:(NSZone *)zone {
    return _instance;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return _instance;
}

@end

三、同步锁


static Share *_instance = nil;

@implementation Share

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

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

- (id)copyWithZone:(NSZone *)zone {
    return _instance;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return _instance;
}

@end

四、同步锁2(前后再次非空判断)


static Share *_instance = nil;

@implementation Share

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

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

- (id)copyWithZone:(NSZone *)zone {
    return _instance;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return _instance;
}

@end
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、不使用GCD的方式 2、使用GCD // 补充再来说说:Objective-C 里的 Alloc 和Alloc...
    Jt_Self阅读 10,911评论 0 1
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,793评论 1 32
  • 单例介绍 本文源码下载地址 1.什么是单例 说到单例首先要提到单例模式,因为单例模式是单例存在的目的 单例模式是一...
    雷鸣1010阅读 8,850评论 0 19
  • 使用Android Studio我们会配置一些模板,比如注释模板,还会修改一些冲突的快捷键,以及一些字体,风格等的...
    慕涵盛华阅读 6,657评论 6 10
  • A1:回顾近一周的安排,你的时间黑洞在哪里?什么时候最容易浪费掉你没有意识到的时间呢? 在平时的生活工作中,习惯于...
    Sophy_CQ阅读 1,566评论 6 5