zoukankan      html  css  js  c++  java
  • iOS开发单例模式 dispatch_once

    什么是单例

    单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。

    iOS开发中如何使用单例

    传统的单例构造方法

    + (id)sharedInstance
    {
        static id sharedInstance;
        if(sharedInstance == nil){
            sharedInstance = [[]self alloc] init]
        }
        return sharedInstance;
    }
    

    多线程下的隐患

    在多线程的情况下,如果两个线程几乎同时调用sharedInstance()方法会发生什么呢?有可能会创建出两个该类的实例。 为了防止这种情况 我们通常会加上锁

    + (id)sharedInstance
    {
        static id sharedInstance;
        @synchronized(self)
            if(sharedInstance == nil){
                sharedInstance = [[]self alloc] init]
            }           
        }
        return sharedInstance;
    }
    

    dispatch_once

    iOS 4.0 引进了 GCD ,其中的 **dispatchonce**,它即使是在多线程环境中也能安全地工作,非常安全。dispatchonce是用来确保指定的任务将在应用的生命周期期间,仅执行一次。以下是一个典型的源代码以初始化的东西。它可以优雅通过使用dispatch_once来创建一个单例。

    + (id)sharedInstance
    {
        static dispatch_once_t once;
        static id sharedInstance;
        dispatch_once(&once, ^{
            sharedInstance = [[self alloc] init];
        });
        return sharedInstance;
    }
    
  • 相关阅读:
    haproxy path_end不能忽略
    haproxy hdr和path
    logstash 分析nginx 错误日志
    logstash 处理nginx 访问日志
    rsyslog 同时发生nginx 访问日志和错误日志
    rsyslog 同时发生nginx 访问日志和错误日志
    【codevs1048】石子归并
    【codevs1576】最长严格上升子序列
    【BAT】中文数字to阿拉伯数字转换
    Windows批处理BAT脚本
  • 原文地址:https://www.cnblogs.com/geek6/p/3870756.html
Copyright © 2011-2022 走看看