下一步我想采用使用共享实例的 GCD 方法,因此我创建了以下代码:
@implementation MyClass
static id sharedInstance;
#pragma mark Initialization
+ (instancetype)sharedInstance {
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (instancetype)init {
if (sharedInstance) {
return sharedInstance;
}
@synchronized(self) {
self = [super init];
if (self) {
sharedInstance = self;
}
return self;
}
}
@end
我假设 sharedInstance
方法似乎没问题,但我不确定 init 方法。创建它的原因是我不希望人们使用我的 SDK,使用 init 方法,如果他们这样做......让它成为防弹的。
最佳答案
我建议完全不允许调用 init,而不是透明地将对 init
的调用重定向到单例实现,这可能会给您的 SDK 用户带来非常困惑的行为:
+ (instancetype)sharedInstance {
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] initPrivate];
});
return sharedInstance;
}
- (instancetype)init {
@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"..." userInfo:nil];
}
- (instancetype)initPrivate {
if (self = [super init]) {
...
}
return self;
}
关于ios - 在 Objective-C 中使用 init 方法创建单例的安全方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29748175/