#import "CoolObject.h"
@implementation CoolObject
+(id)shareInstance {
static CoolObject *instance = nil;
static dispatch_once_t token;
dispatch_once(&token, ^{
// 必须使用super防止循环调用 self和CoolObject一样都会导致循环调用
instance = [[super allocWithZone:NULL] init];
});
return instance;
}
/// 防止有人使用allocWithZone创建对象
/// @param zone 一般传null
+(instancetype)allocWithZone:(struct _NSZone *)zone {
return [self shareInstance];
}
/// 防止有人使用copy 单例对象
/// @param zone
-(id)copyWithZone:(NSZone *)zone {
return self;
}
@end
测试:
CoolObject *instance = [CoolObject shareInstance];
CoolObject *copyInstance = [instance copy];
CoolObject *zoneInstance = [[CoolObject allocWithZone:nil] init];
NSLog(@"instance: %p %p %p", instance, copyInstance, zoneInstance);
//输出
instance: 0x600000a38230 0x600000a38230 0x600000a38230
网友评论