我試圖實現一個類,該子類直接從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