在界面生成器中使用Singleton? [英] Use Singleton In Interface Builder?
问题描述
我的单例设置如下:
static Universe *instance;
+ (Universe *)instance { return instance; }
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
instance = [[Universe alloc] init];
}
}
- (id) init
{
self = [super init];
if (self != nil) {
self.showHistory = YES;
}
return self;
}
但是现在我意识到我想从Interface Builder实例化它.我当时想像这样切入init
方法
but now I realize that I'd like to instantiate it from Interface Builder. I was thinking of just cutting into the init
method like so
if (instance)
return instance;
这是个坏主意吗?我希望IB来选择已经在+initialize
方法中创建的实例.
is this a bad idea? I'd prefer IB to pick up the instance already created in the +initialize
method.
推荐答案
这可以完成. Buck和Yachtman的可可设计模式中有关于这一部分的内容.
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;
}
然后,笔尖加载代码将通过调用[[Universe alloc] init]
正确拾取单例,并且您仍然可以像以前一样在代码中使用instance
.
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.
这本书有更多详细信息,并建议实现new
和allocWithZone
(都简单地称为return [self alloc];
),以及错误报告存根以捕获copyWithZone
和mutableCopyWithZone
的尝试,以取得良好的效果.
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.
这篇关于在界面生成器中使用Singleton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!