最近面试的时候,面试官让我写下单例,我是如下写的
+ (Singleton *)sharedSingleton{
static Singleton *singleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
singleton = [[Singleton alloc]init];
});
return singleton;
}
但是面试官看了看说如果这样写的话是保证了线程安全,但是如果要是直接 [[Singleton alloc]init] 的话还是不能保证该对象只被创建一次,他说需要重载下+new, +alloc,+allocWithZone:, -copyWithZone:, 以及 -mutableCopyWithZone这些方法,请问真的是这样吗?给我解答下吧