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.
Currently I have this approach:
// MyClass.h
@interface MyClass : NSObject
+(MyClass *) instance;
@end
And the implementation:
// 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?
Thanks