单例的2种写法

单例模式是iOS开发中最常用的设计模式,iOS的单例模式有两种官方写法,如下:

1,常用写法

import "ServiceManager.h"

static ServiceManager *defaultManager;

@implementation ServiceManager

+(ServiceManager *)defaultManager{
if(!defaultManager)
defaultManager=[[self allocWithZone:NULL] init];
return defaultManager;
}

@end

2,用GCD创建单例类

import "ServiceManager.h"

@implementation ServiceManager

+(ServiceManager *)sharedManager{
static dispatch_once_t predicate;
static ServiceManager * sharedManager;
dispatch_once(&predicate, ^{
sharedManager=[[ServiceManager alloc] init];
});
return sharedManager;
}

@end

其中dispatch_once函数只执行一次。

你可能感兴趣的:(单例的2种写法)