• [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; 

  • 相关阅读:
    LeetCode 39. Combination Sum
    LeetCode 37. Sudoku Solver
    LeetCode 36. Valid Sudoku
    LeetCode 34. Search for a Range
    LeetCode 33. Search in Rotated Sorted Array
    VS2010出现灾难性错误的解决办法
    双系统下利用MbrFix.exe卸载LINUX系统
    VS 与 SQLite数据库 连接
    人月神话阅读笔记2
    关于疫情数据分析web开发2-网页爬取实现
  • 原文地址:https://www.cnblogs.com/jinjiantong/p/2976367.html
Copyright © 2020-2023  润新知