IOS - 单例模式+多线程

比如车票类Ticket,保证票只创建了一次。

1.定义静态全局变量 static Ticket *SharedInstance;

 定义一个票数的变量 @property(assign,atomic)NSInteger tickets;

atomic 原子属性,在多线程中一个线程访问了其他线程不能访问了。

另外加同步锁@synchronized

2.新建一个车票类,重写allocWithZone方法

+(id)allocWithZone:(NSZone *)zone

{

  //多线程

  static dispath_once_t onceToken;

  dispath_once(&onceToken,^{

    SharedInstance = [super allocWithZone:zone];

  });

  //单线程

  //if(SharedInstance == nil)

  //{

  //  SharedInstance = [super allocWithZone:zone];

  //}

  return SharedInstance;

}

3.便于调用

+(Ticket*)sharedTicket

{

  static dispatch_once_t onceToken;

  dispatch_one(&onceToken,^{

    SharedInstance = [[Ticket alloc]init];

  });

  return ticket;

}

原文地址:https://www.cnblogs.com/zhouwenbo/p/4446795.html