實現單例,首先遵循NSCopy協議(遵循協議是為了重寫協議中的方法)
- 在MRC下的示例代碼:
#import "AudioTools.h"
@implementation AudioTools
static id _instanceType = nil;
// 自定義類方法創建單例
+(instancetype)sharadAudioTools{
//一次性執行實現單例
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instanceType = [[self alloc]init];
});
return _instanceType;
}
// 嚴謹寫法需要重寫此方法,避免alloc]init或new實例化新對象
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instanceType = [super allocWithZone:zone];
});
return _instanceType;
}
// 防止對象Copy操作 (一般此方法默認只對NSString類型有效)
-(id)copyWithZone:(NSZone *)zone{
return _instanceType;
}
//MRC下防止手動銷毀對象(重寫后不執行任何操作)
-(oneway void)release{
}
//以下為其他引用計數器操作方法
-(instancetype)retain{
return _instanceType;
}
-(instancetype)autorelease{
return _instanceType;
}
- (NSUInteger)retainCount{
return 1;
}
@end
- 在ARC下示例代碼:
#import "NetWorkTools.h"
@implementation NetWorkTools
static id _instanceType = nil;
//自定義類方法
+(instancetype)sharadNetWorkTools{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instanceType = [[self alloc]init];
});
return _instanceType;
}
//重寫父類方法,防止通過alloc]init或new的方式開辟新空間
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instanceType = [super allocWithZone:zone];
});
return _instanceType;
}
//防止對象copy操作
-(id)copyWithZone:(NSZone *)zone{
return _instanceType;
}
@end