Objective-C仅使用一个实例创建类的正确方法 [英] Objective-C Proper way to create class with only one instance

查看:66
本文介绍了Objective-C仅使用一个实例创建类的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个直接为NSObject子类的类,该类在使用它的应用程序运行的整个过程中只能有一个实例.

I am trying to implement a class, that subclasses NSObject directly, that can only have one instance available throughout the entire time the application using it is running.

目前我有这种方法:

// MyClass.h

@interface MyClass : NSObject

+(MyClass *) instance;

@end

执行:

// MyClass.m

// static instance of MyClass
static MyClass *s_instance;

@implementation MyClass

-(id) init
{
    [self dealloc];
    [NSException raise:@"No instances allowed of type MyClass" format:@"Cannot create instance of MyClass. Use the static instance method instead."];

    return nil;
}

-(id) initInstance
{
    return [super init];
}

+(MyClass *) instance {
    if (s_instance == nil)
    {
        s_instance = [[DefaultLiteralComparator alloc] initInstance];
    }

    return s_instance;    
}

@end

这是完成这项任务的正确方法吗?

Is this the proper way to accomplish such a task?

谢谢

推荐答案

您还需要做更多的事情.这描述了应如何实现Objective-C单例: Objective-C单例

You need to do a little more than that. This describes how an objective-c singleton should be implemented: Objective-C Singleton

这篇关于Objective-C仅使用一个实例创建类的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆