zoukankan      html  css  js  c++  java
  • OC基础 单例

    #undef  AS_SINGLETON  
        #define AS_SINGLETON( __class )   
                + (__class *)sharedInstance;  
              
            #undef  DEF_SINGLETON  
            #define DEF_SINGLETON( __class )   
                    + (__class *)sharedInstance   
                    {   
                        static dispatch_once_t once;   
                        static __class * __singleton__;   
                       dispatch_once( &once, ^{ __singleton__ = [[__class alloc] init]; } );   
                        return __singleton__;   
                }  

    上面是用宏来定义单例。

    下面介绍我们常用的两种单例的写法:

    第一种

    static SingleClass *single = nil;
    + (id)shareInstance {
        if(!single)
        {
            single = [[SingleClass alloc] init];
        }
        return single;
    }

    第二种

    + (id)shareInstance
    {
        static SingleClass *single = nil;
        static dispatch_once_t predicate;
        dispatch_once(&predicate, ^{
            single = [[self alloc] init];
        });
        return single;
    }
  • 相关阅读:
    Investment
    The Fewest Coins
    Bone Collector II
    Cow Exhibition
    饭卡
    A + B Problem II
    F
    敌兵布阵
    单例模式
    面向对象
  • 原文地址:https://www.cnblogs.com/DWdan/p/4875086.html
Copyright © 2011-2022 走看看