怎么销毁单例

发布时间 2023-07-12 10:33:14作者: 丷dante丶灬
static NGUser *sharedInstance = nil;
static dispatch_once_t onceToken;
+ (instancetype)sharedInstance{
  
  dispatch_once(&onceToken, ^{
      //调用父类的allocWithZone,不能使用self,避免循环引用
      sharedInstance = [[super allocWithZone:NULL] init];
  });
  return sharedInstance;
}

//必须要实现的,当我们创建一个对象,alloc会给对象分配内存,init初始化数据
//alloc会调用allocWithZone,如果创建对象没有使用sharedInstance,而是使用alloc
//那么alloc就会调用allocWithZone,重写类方法,调用sharedInstance使得alloc时创建的也是单例对象
+(instancetype)allocWithZone:(struct _NSZone *)zone{
  return [self sharedInstance];
}

//单例对象被copy
-(id)copyWithZone:(nullable NSZone *)zone{
  return self;
}
+(void)attempDealloc{
  onceToken = 0; // 只有置成0,GCD才会认为它从未执行过.它默认为0.这样才能保证下次再次调用shareInstance的时候,再次创建对象.
  sharedInstance = nil;
}