ARC和MRC实现单例

1.2 ARC实现单例

  • (1)步骤
    01 在类的内部提供一个static修饰的全局变量
    02 提供一个类方法,方便外界访问
    03 重写+allocWithZone方法,保证永远都只为单例对象分配一次内存空间
    04 严谨起见,重写-copyWithZone方法和-MutableCopyWithZone方法
static Tool *_instanceTool;

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

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

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

MRC下的单例


static Tool *_instanceTool;

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

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

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

 - (void)release{
}
- (instancetype)retain{
    return _instanceTool;
}

- (NSUInteger)retainCount
{
    return MAXFLOAT;
}

ARC和MRC通用的宏

#define SingleH(name) +(instancetype)share##name;

#if __has_feature(objc_arc)
//条件满足 ARC
#define SingleM(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\
{\
return [[self alloc]init];\
}\
\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
\
-(id)mutableCopyWithZone:(NSZone *)zone\
{\
return _instance;\
}

#else
//MRC
#define SingleM(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\
{\
return [[self alloc]init];\
}\
\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
\
-(id)mutableCopyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
-(oneway void)release\
{\
}\
\
-(instancetype)retain\
{\
return _instance;\
}\
\
-(NSUInteger)retainCount\
{\
return MAXFLOAT;\
}
#endif


你可能感兴趣的:(ARC和MRC实现单例)