使用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];