zoukankan      html  css  js  c++  java
  • [ios]单例

    http://blog.csdn.net/mars2639/article/details/7283741

    static Singleton * sharedInstance = nil;  

       

    @implementation Singleton  

       

    //获取单例  

    +(Singleton *)sharedInstanceMethod  

    {  

        @synchronized(self) {  

            if (sharedInstance == nil)  

          sharedInstance = [[self alloc] init];  

            }  

        }  

        return sharedInstance;  

    }  

       

    //唯一一次alloc单例,之后均返回nil  

    + (id)allocWithZone:(NSZone *)zone  

    {  

        @synchronized(self) {  

            if (sharedInstance == nil) {  

                instance = [super allocWithZone:zone];  

                return instance;  

            }  

        }  

        return nil;  

    }  

       

    //copy返回单例本身  

    - (id)copyWithZone:(NSZone *)zone  

    {  

        return self;  

    }  

       

    //retain返回单例本身  

    - (id)retain  

    {  

        return self;  

    }  

       

    //引用计数总是为1  

    - (unsigned)retainCount  

    {  

        return 1;  

    }  

       

    //release不做任何处理  

    - (void)release  

    {  

         

    }  

       

    //autorelease返回单例本身  

    - (id)autorelease  

    {  

        return self;  

    }  

       

    //  

    -(void)dealloc  

    {  

          [super dealloc];  

    }  

       

    @end 

    ios5 有了arc以后就这样简单

    static RootViewController* sharedRootController = nil;
     
    +(RootViewController *) sharedController{
        @synchronized(self){
            if (sharedRootController == nil) {
               sharedRootController = [[self alloc] init];
            }
        }
        return  singleController;
    }

    还有一种方法

       static AccountManager *sharedAccountManagerInstance = nil;  

            static dispatch_once_t predicate;  

            dispatch_once(&predicate, ^{  

                    sharedAccountManagerInstance = [[self alloc] init];   

            });  

        return sharedAccountManagerInstance; 

  • 相关阅读:
    我的第一颗二叉链树的笔记
    我的kmp笔记
    链表操作笔记
    POJ 2559 Largest Rectangle in a Histogram (单调栈)
    牛客网 wyh的数列(循环节+快速幂)
    数论知识点
    牛客网 n的约数 (唯一分解定理)
    POJ 3783 Balls (DP)
    关于unordered_map和map
    2018年四校联合周赛-第二场 B.异或和问题(二维树状数组)
  • 原文地址:https://www.cnblogs.com/jinjiantong/p/2976367.html
Copyright © 2011-2022 走看看