OC中单例的各种写法及基本讲解

1、典型的单例写法

1 static id sharedMyManager;
2 +(id)shareThemeManager{
3     if(sharedThemeManager == nil){
4              shareMyManager = [[self alloc]init];
5     }
6   return sharedMyManager;
7 }

缺点:无法保证多线程情况下只创建一个对象。适用于只有单线程。

2、加锁的写法:

 1 static sharedManager* single = nil;
 2 
 3 +(sharedManage*)sharedManage{
 4 
 5     @synchronized(self){   //加锁,保证多线程下也只能有一个线程进入
 6 
 7         if (!single) {
 8 
 9             single = [[self alloc]init];
10 
11         }
12 
13     }
14 
15     return single;
16 
17 }

这种方法较常用。

3、GCD写法:

static sharedManager * single = nil;
+(id)sharedManager{

     static dispatch_once_t once;

      dispatch_once(&once,^{
               single = [[self alloc]init];
});

return single;
}

4、免锁(Lock free)的写法:

 1 static sharedManager * single = nil;
 2 
 3     +(void)initialize{
 4  
 5      static BOOL initialized = NO;
 6  
 7      if (initialized == NO){
 8  
 9          initialized = YES;
10  
11          shareMyManager = [[self alloc]init];
12 
13           }
14  
15  }

单例全面的写法:

重载以下方法:

+(id)allocWithZone:(NSZone *)zone;

+(id)copyWithZone:(NSzone *)zone;

+(id)retain;

+(void)release; //单例里面重写单例不允许release,autorrelease,所以重写

+(void)autorelease;

原文地址:https://www.cnblogs.com/shaoting/p/4889872.html