您的位置:首页 > 其它

dispatch_once函数之单例模式

2016-03-18 16:30 239 查看
使用dispatch_once函数可以简化代码并且保证线程安全。变量只需要初始化一次,保证只调用API一次。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"该行代码只执行一次");
});
}

单例设计模式确保对于一个给定的类只有一个实例存在,这个实例有一个全局唯一的访问点。因为单例类的静态实例对象需要唯一性,故只能是static类型。

@implementation XXClass

+ (instancetype)sharedInstance {
static XXClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (!sharedInstance) {
sharedInstance = [[self alloc] init];
}
});
return sharedInstance;
}
我们调用只需要一句话。

XXClass *sharedInstance = [XXClass sharedInstance];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息