您还必须重写该+alloc
方法以避免分配多个单例实例。
编辑#3: 嗯,我真的知道官方文档中关于覆盖该 +alloc
方法的内容,但是要实现所要求的好处,没有办法避免它。我个人不同意这样做,但它可以提供预期的结果。
它会是这样的:
static MyClass *_sharedInstance = nil;
static BOOL _bypassAllocMethod = TRUE;
+ (id)sharedInstance {
@synchronized([MyClass class]) {
if (_sharedInstance == nil) {
_sharedInstance = [[MyClass alloc] init];
}
}
return _sharedInstance;
}
+ (id)alloc {
@synchronized([MyClass class]) {
_bypassAllocMethod = FALSE; // EDIT #2
if (_sharedInstance == nil) {
_sharedInstance = [super alloc];
return _sharedInstance;
} else {
// EDIT #1 : you could throw an exception here to avoid the double allocation of the singleton class
@throw [NSException exceptionWithName:[NSString stringWithFormat:@"<%@: %p> Double allocation issue", [_sharedInstance class], _sharedInstance] reason:@"You cannot allocate the singeton class twice or more." userInfo:nil];
}
}
return nil;
}
// EDIT #2 : the init method
- (id)init {
if (_bypassAllocMethod)
@throw [NSException exceptionWithName:@"invalid allocation" reason:@"invalid allocation" userInfo:nil];
if (self = [super init]) {
}
return self
}
编辑#1
您绝对不需要在这里抛出异常,但是对于他们以错误方式使用您的类的开发人员来说,这比发回简单的nil
指针要多得多的视觉反馈。
编辑#2
我添加了一个简单的技巧来避免开发人员实例化该类以绕过修改后的+alloc
方法,在这种情况下分配将正常工作,但-init
会引发异常。