• iOS 单例


    1. 单例的理解

                单例模式在他的核心结构中只包含一个叫单例的特殊类,他只有一个实例对象并且易于外部访问,

           从而实现对实例个数的控制,并且减少系统资源,如果想要实现实例对象只有一个,那么单例模式是你最好的选择。  

          2.单例创建步骤

    •  创建一个类方法,名字以shared,default current开头。  
    •  创建一个全局变量来保存对象的引用。  
    •  判断该对象是否存在,如果没有则创建。

           3.单例写法。  

      • 非线程安全的单例        

                       /**  *  非线程安全的单例  *  *  @return  */

                     + (instancetype)defaultPerson {    

                      //创建一个全局变量,以保存对象的引用    

                         static Person *person = nil;    

                                if (person == nil) {        

                                       person = [[self alloc]init];  

                                   }    

                          return person;

                         }

      •  线程安全单例写法1 - 加了一个互斥锁        

                      + (instancetype)defaultPerson {  

                  static Person *person = nil;      

              @synchronized(self) {        

                 if (person == nil) {          

                      person = [[self alloc]init];      

                  }    

              }    

              return person;

           }

      • 线程安全单例写法2        

           + (void)initialize {  

                static Person *person = nil;      

                if([self class] == [Person class])     {      

                      person = [[Person alloc]init];  

                    }

           }

      • 线程安全单例写法3 -- GCD,苹果推荐的          

          + (instancetype)defaultPerson {  

              static Person *person = nil;    

             static dispatch_once_t onceToken;  

              dispatch_once(&onceToken, ^{      

                 person = [[self alloc]init];  

              });  

            return person;

          }

  • 相关阅读:
    sql developer 中文乱码解决办法
    ubuntu oracle数据库18c安装
    ubuntu Oracle SQL Developer 安装
    web.xml is missing and <failOnMissingWebXml> is set to true
    MySQL设置快速删除
    Annoying “Remote System Explorer Operation” causing freeze for couple of seconds
    安装程序时出现2502 2503错误解决方法
    Smoke Testing(冒烟测试)
    MySQL5.7.11免安装版的安装和配置:解决MYSQL 服务无法启动问题
    Error 2503 and 2502 when installing/uninstalling on Windows 10
  • 原文地址:https://www.cnblogs.com/liu-lang/p/5522557.html
Copyright © 2020-2023  润新知