zoukankan      html  css  js  c++  java
  • IOS 单例 创建方式

    @implementation Me

    static Car *sharedInstance= nil;//声明一个静态对象引用并赋为nil

     

    +(Me *) sharedInstance//声明类方法(+为类方法,也就是Java中的静态方法)

    {

         if(!sharedInstance)

         {

              sharedInstance = [[self alloc] init];

         }

         return sharedInstance;

    }

    @end

     

    //覆盖allocWithZone:方法可以防止任何类创建第二个实例。使用synchronized()可以防止多个线程同时执行该段代码(线程锁)

     

    +(id)allocWithZone:(NSZone *) zone

    {

         @synchronized(self)

         {

              if(sharedInstance == nil)

              {

                   sharedInstance = [super allocWithZone:zone];

                   return sharedInstance;

              }

         }

         return sharedInstance;

    }

     直接类名调用类方法就行了

  • 相关阅读:
    Python Day13:开放封闭原则、函数装饰器、全局局部变量
    Python Day12
    Python Day11
    Python Day10
    drf框架
    drf框架
    drf框架
    drf框架
    vue框架
    vue框架
  • 原文地址:https://www.cnblogs.com/mohe/p/3443486.html
Copyright © 2011-2022 走看看