• 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;

    }

  • 相关阅读:
    MVC过滤器
    MVC自带的校验
    FPGA简单概述
    CAN总线扩展数据帧介绍
    简述人工智能发展的先决条件
    CAN总线标准帧
    CAN总线应用
    CAN总线优点
    CAN总线概述
    高速PCB设计注意事项
  • 原文地址:https://www.cnblogs.com/zhouwenbo/p/4446795.html
Copyright © 2020-2023  润新知