首页 > 代码库 > ARC和MRC 兼容的单例模式

ARC和MRC 兼容的单例模式

一、ARC下的单例实现

  说明:在用户实例化的方法控制单次执行,同时开放单例的初始化方法。

-(instancetype)init{

    self=[super init];
    if(self){
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
        });
    }
    return self;
    

}

static id instance; 
+(instancetype)allocWithZone:(struct _NSZone *)zone{ 
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{ 
    instance=[super allocWithZone:zone]; 
    }); 
return instance;
} 
 
 
+ (instancetype) shareAudio{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{ 
    instance=[[self alloc]init]; 
    }); 
    return instance; 
} 
 
+(id)copyWithZone:(struct _NSZone *)zone{ 
    return instance;
}
二、MRC下的单例实现

   说明:在用户实例化的方法控制单次执行,同时开放单例的初始化方法,由于当前为MRC所以需要控制参内存管理的方法单次执行,因此相比ARC需要增加:

static id instance; 
+(instancetype)allocWithZone:(struct _NSZone *)zone{ 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
        instance=[super allocWithZone:zone]; 
    }); 
    return instance; 
} 
 
 
+ (instancetype) shareAudio{
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
        instance=[[self alloc]init]; 
    }); 
    return instance; 
} 
-(oneway void)release{ 
} 
 
-(instancetype)autorelease{ 
    return instance; 
} 
 
-(instancetype)retain{ 
    return instance; 
} 
 
-(NSUInteger)retainCount{ 
    return 1; 
}
三、兼容MRC 和ARC的宏定义

   说明:为了方便后期的引用,可以将单例抽取为宏定义,鉴于抽取的时候考虑到当前的手动计数和自动计数因此引入条件编译:

#if !__has_feature(objc_arc)
======当前是ARC
#else
======当前是MRC
#endif

代码:
#define singleton_h(name)  + (instancetype) share##name;


#if !__has_feature(objc_arc)
#define singleton_m(name) static id instance;+(instancetype)allocWithZone:(struct _NSZone *)zone{    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        instance=[super allocWithZone:zone];    });    return instance;}+ (instancetype) share##name{    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        instance=[[self alloc]init];    });    return instance;}-(oneway void)release{}-(instancetype)autorelease{    return instance;}-(instancetype)retain{    return instance;}+(id)copyWithZone:(struct _NSZone *)zone{    return instance;}-(NSUInteger)retainCount{    return 1;}

#else

#define singleton_m(name)static id instance;+(instancetype)allocWithZone:(struct _NSZone *)zone{  static dispatch_once_t onceToken;  dispatch_once(&onceToken, ^{  instance=[super allocWithZone:zone];});  return instance;}+ (instancetype) share##name{  static dispatch_once_t onceToken;  dispatch_once(&onceToken, ^{   instance=[[self alloc]init];  });  return instance;}+(id)copyWithZone:(struct _NSZone *)zone{   return instance;}
#endif
四、文件引用

1 在.h文件引用singleton_h(audio);

2 在.m文件引用singleton_m(audio);

ARC和MRC 兼容的单例模式