//PerfectSingleton.h
#import@interface PerfectSingleton : NSObject
+ (instancetype)Shareinstance;
@end
// PerfectSingleton.m
#import "PerfectSingleton.h"
PerfectSingleton *manager = nil;
@implementation PerfectSingleton
+ (instancetype)Shareinstance{
if(!manager){
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [PerfectSingleton new];
});
}
return manager;
}
// 防止使用alloc开辟空间
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
if(!manager){
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [super allocWithZone:zone];
});
}
return manager;
}
// 防止copy
+ (id)copyWithZone:(struct _NSZone *)zone{
if(!manager){
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [super copyWithZone:zone];
});
}
return manager;
}
// 使用同步锁保证init创建唯一单例 ( 与once效果相同 )
- (instancetype)init{
@synchronized(self) {
self = [super init];
}
return self;
}
@end
网友评论