您的位置:首页 > 移动开发 > IOS开发

IOS 单例模式

2016-03-26 15:02 246 查看
#import "Singleton.h"

@implementation Singleton

static Singleton* _instance = nil;

+(instancetype) shareInstance
{
static dispatch_once_t onceToken ;
dispatch_once(&onceToken, ^{
_instance = [[super allocWithZone:NULL] init] ;
}) ;

return _instance ;
}

+(id) allocWithZone:(struct _NSZone *)zone
{
return [Singleton shareInstance] ;
}

-(id) copyWithZone:(struct _NSZone *)zone
{
return [Singleton shareInstance] ;
}

@end


使用:

Singleton* obj1 = [Singleton shareInstance] ;
NSLog(@"obj1 = %@.", obj1) ;

Singleton* obj2 = [Singleton shareInstance] ;
NSLog(@"obj2 = %@.", obj2) ;

Singleton* obj3 = [[Singleton alloc] init] ;
NSLog(@"obj3 = %@.", obj3) ;

Singleton* obj4 = [[Singleton alloc] init] ;
NSLog(@"obj4 = %@.", [obj4 copy]) ;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: