我试图实现一个类,该子类直接从NSObject
开始,只能有一个实例在整个应用程序中都可用。Objective-C创建只有一个实例的类的正确方法
目前我有这种做法:
// 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
这是为了完成这样的任务的正确方法?
谢谢
谢谢,我会用这个解决方案! – 2010-10-12 01:18:54
另请参阅http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like – sdolan 2010-10-12 01:23:21
不错的链接,帮了我很多! – 2010-10-12 01:32:28