在软件工程中,单例是一种用于实现单例的数学概念,即将类的实例化限制成仅一个对象的设计模式。
单例是一种类,该类只能实例化一个对象。
void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);
如果被多个线程调用,该函数会同步等等直至代码块完成。
+ (AccountManager *)sharedManager {
static AccountManager *sharedAccountManagerInstance = nil;
static dispatch_once_t predicate; dispatch_once(&predicate, ^{
sharedAccountManagerInstance = [[self alloc] init];
});
return sharedAccountManagerInstance;
}
AccountManager *accountManager = [AccountManager sharedManager];
AccountManager *accountManager = [[AccountManager alloc] init];
static MyMontionManager *_instance;
@implementation MyMontionManager
+ (id)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
+ (instancetype)sharedMyMontionManager
{
if (_instance == nil) {
_instance = [[MyMontionManager alloc] init];
}
return _instance;
}
@end
利用dispatch_once创建单例,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/yjg2014/p/3862401.html