Objective-C使用一个实例创建类的正确方法
我试图实现一个类,即直接将Objective-C使用一个实例创建类的正确方法,objective-c,initialization,Objective C,Initialization,我试图实现一个类,即直接将NSObject子类化,在使用它的应用程序运行的整个过程中,只能有一个实例可用 目前我有这种方法: // MyClass.h @interface MyClass : NSObject +(MyClass *) instance; @end 以及实施: // MyClass.m // static instance of MyClass static MyClass *s_instance; @implementation MyClass -(id) in
NSObject
子类化,在使用它的应用程序运行的整个过程中,只能有一个实例可用
目前我有这种方法:
// 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
这是完成这项任务的正确方法吗
谢谢您需要做的不仅仅是这些。这描述了如何实现objective-c单例:在您的场景中,仍然有一种方法可以创建类的第二个实例:
MyClass *secondInstance = [[MyClass alloc] initInstance]; //we have another instance!
您想要的是重写类的+(id)alloc
方法:
+(id)alloc{
@synchronized(self){
NSAssert(s_instance == nil, @"Attempted to allocate a second instance of singleton(MyClass)");
s_instance = [super alloc];
return s_instance;
}
return nil;
}
是的,但是
initInstance
方法不在头中,只在实现中…您将得到一个编译器警告,但仅此而已。它仍将运行,并创建第二个实例。此外,没有任何东西禁止类的方法创建自身的另一个实例。实际上,您不会收到编译器警告,因为initInstance的定义在其唯一用途之前。谢谢,我将使用此解决方案!另请参见@ennuikiller链接已断开。看一看。