我有一个我希望实现为单例的类。
我希望创建/访问此类实例的唯一方法是通过:
+(MYClass*)sharedInstance
方法。 alloc 和 init 在方法实现中被调用(当然)。
如果尝试创建该类的实例而不是通过 sharedInstance 方法(而是直接通过 alloc + init),有没有办法阻止 alloc 和 init 的使用,或者使它们“空”?
最佳答案
如果在实现之外调用 init
,将此代码放在头文件中应该会产生编译时错误:
- (id)init __attribute__((unavailable("cannot use init for this class, use +(MYClass*)sharedInstance instead")));
我发现了这个技巧 here .
更新:
您将无法在 .m 文件中编写 [[MYClass alloc] init]
但您可以使用以下内容:
+ (MYClass *)sharedInstance {
static MYClass *sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [self new];
});
return sharedInstance;
}
关于ios - 单例实现。阻止外部使用的 alloc 和 init 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20867180/