iOS单例模式线程安全问题

 #import "DemoObj.h"

@implementation DemoObj

static DemoObj *instance;

/**

 1. 重写allocWithZone,用dispatch_once实例化一个静态变量

 2. 写一个+sharedXXX方便其他类调用

 */

// 在iOS中,所有对象的内存空间的分配,最终都会调用allocWithZone方法

// 如果要做单例,需要重写此方法

// GCD提供了一个方法,专门用来创建单例的

 1 + (id)allocWithZone:(struct _NSZone *)zone
 2 
 3 {
 4 
 5     static DemoObj *instance;
 6 
 7     
 8 
 9     // dispatch_once是线程安全的,onceToken默认为0
10 
11     static dispatch_once_t onceToken;
12 
13     // dispatch_once宏可以保证块代码中的指令只被执行一次
14 
15     dispatch_once(&onceToken, ^{
16 
17         // 在多线程环境下,永远只会被执行一次,instance只会被实例化一次
18 
19         instance = [super allocWithZone:zone];
20 
21     });
22 
23     
24 
25     return instance;
26 
27 }
28 
29  
30 
31 + (instancetype)sharedDemoObj
32 
33 {
34 
35     // 如果有两个线程同时实例化,很有可能创建出两个实例来
36 
37 //    if (!instance) {
38 
39 //        // thread 1 0x0000A
40 
41 //        // thread 2 0x0000B
42 
43 //        instance = [[self alloc] init];
44 
45 //    }
46 
47 //    // 第一个线程返回的指针已经被修改!
48 
49 //    return instance;
50 
51     return [[self alloc] init];
52 
53 }
54 
55  
56 
57 @end
原文地址:https://www.cnblogs.com/qq449832375/p/4671850.html