1、@synchronized
static InstanceClass *instance;
+ (InstanceClass *)defaultInstance{
@synchronized (self){
if (instance == nil) {
instance = [[InstanceClass alloc] init];
}
}
return instance;
}
2、GCD
static InstanceClass *instance;
+ (InstanceClass *)defaultInstance{
static dispatch_once_t onceToken;
dispatch_once (&onceToken, ^{
instance = [[InstanceClass alloc] init];
});
return instance;
}
两种方式都能起到线程安全的作用,尤其是在多cpu的环境下