This can be done. There is a section about it in Cocoa Design Patterns by Buck and Yachtman.
In your case you could do something along the lines of:
static Universe *instance;
+ (Universe *)instance { return instance; }
+ (id)hiddenAlloc
{
return [super alloc];
}
+ (id)alloc
{
return [[self instance] retain];
}
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
instance = [[Universe hiddenAlloc] init];
}
}
- (id)init
{
if(instance==nil) // allow only to be called once
{
// your normal initialization here
}
return self;
}
The nib loading code will then correctly pick up the singleton via its call to [[Universe alloc] init]
, and you can still use instance
in your code as before.
The book has more detail and recommends implementing new
and allocWithZone
(both simply as return [self alloc];
), plus error-reporting stubs to catch copyWithZone
and mutableCopyWithZone
attempts for good measure.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…