ARC环境下的单例模式:
static id _instance = nil;
+ (id)allocWithZone:(struct _NSZone *)zone
{
if (_instance == nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
}); } return _instance; } - (id)init
{ static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super init];
});
return _instance;
} + (instancetype)sharedMethodName
{
return [[self alloc] init];
}
非ARC模式下的单例模式:
static id _instance = nil;
+ (id)allocWithZone:(struct _NSZone *)zone
{
if (_instance == nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
}); } return _instance; } - (id)init
{ static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super init];
});
return _instance;
} + (instancetype)sharedMethodName
{
return [[self alloc] init];
} - (oneway void)release
{ } - (id)retain
{
return self;
} - (NSUInteger)retainCount
{
return ;
}
如何判断当前的环境是arc还是非arc 可以这样写:
#if __has_feature(objc_arc) //是arc
//这里写arc下的代码
#else //非arc
//这里写非acr下的代码
#endif