ios - 单例实现。阻止外部使用的 alloc 和 init 方法

标签 ios singleton init alloc singleton-methods

我有一个我希望实现为单例的类。

我希望创建/访问此类实例的唯一方法是通过:

+(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/

相关文章:

iphone - 为什么仪器无法跟踪我的内存使用情况?

grails - Grails范围为Singleton,许多用户登录并执行操作

ios - 在 Swift 中将参数传递给操作函数

ios - UITextField 中 Caret/Cursor 的奇怪行为

design-patterns - 如何回答面试题: What is a singleton and how would you use one?

java - 单例实例化

swift - 没有为 SKShapeNode 指定初始化(circleOfRadius : radius)

c - 如何从C程序向Linux中的控制台发送广播消息

Gitkraken 工作流程 : how to Init local and remote?

ios - 了解 Swift 中的崩溃报告(部分应用...)