实现单例,首先遵循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