Objective-C 创建单例
程序开发(Objective-C)中,经常要用到单例,其创建代码如下:
static Car *sharedInstance = nil;
#pragma mark Single instance
+ (Car *)sharedInstance {
if (!sharedInstance) {
sharedInstance = [[self alloc] init];
}
return sharedInstance;
}
+ (id)allocWithZone:(struct _NSZone *)zone {
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [super allocWithZone:zone];
return sharedInstance;
}
}
return nil;
}
说明:
- 覆盖allocWithZone:方法的目的是为了防止任何类创建第二个实例;
- @synchronized指令防止多线程同时调用该代码块;