【iOS系列】-单例模式的实现

1:重写allocWithZone方法
allocWithZone方法是对象分配内存空间时, alloc方法最终会调用这个方法

+ (id)allocWithZone:(struct _NSZone *)zone
{
static Xxxx *instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [super allocWithZone:zone];
});
return instance;
}

2:建立sharedXxxx类方法,便于其他类访问

+ (instancetype)sharedXxxx
{
return [[self alloc] init];
}

你可能感兴趣的:(单例模式)