Use alloc method to initialize an instance of the class time, the default method is called allocWithZone.
Rewrite allocWithZone method \
// rewrite allocWithZone: method, created here a unique instance (note thread-safe)
static id _instance;
+(instancetype)alloc
{
return [super allocWithZone:nil];
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
// class methods provide a unique instance access to the outside world
+ (instancetype)sharedInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init];
});
return _instance;
}
// achieve copyWithZone: Methods
- (id)copyWithZone:(struct _NSZone *)zone
{
return _instance;
}