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

posted @ 2013-03-22 21:47  金建彤  阅读(191)  评论(0编辑  收藏  举报