您的位置:首页 > 移动开发 > Objective-C

Objective-C 单例模式

2015-06-27 20:09 459 查看
加锁的写法:

static id sharedMyManager;
+ (id)sharedThemeManager
{
@synchronized(self)
{
if(sharedMyManager == nil)
{
sharedMyManager = [[self alloc] init];
}
}
return sharedMyManager;
}


第一次实例化创建Lock free:

static id sharedMyManager;

+ (void)initialize
{
static BOOL initialized = NO;
if (initialized == NO) {
initialized = YES;
sharedMyManager  = [[self alloc] init];
}
}


GCD写法:
static id sharedMyManager;
+ (id)sharedManager
{
static dispatch_once_t once;
dispatch_once(&once, ^{sharedMyManager = [[self alloc] init];});
return sharedMyManager;
}


+ (id)allocWithZone:(struct _NSZone *)zone

{

return [self sharedManager];

}

+ (id)copyWithZone:(struct _NSZone *)zone

{

return self;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: