我正在尝试直接实现一个类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
这是完成这项任务的正确方法吗?
由于
答案 0 :(得分:7)
你需要做更多的事情。这描述了如何实现Objective-c单例:Objective-C Singleton
答案 1 :(得分:0)
在您的方案中,仍有一种方法可以创建类的第二个实例:
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;
}