我的问题与这个问题非常相似:在 Interface Builder 中使用 Singleton? https://stackoverflow.com/questions/4609609/use-singleton-in-interface-builder
唯一的区别是我使用 ARC。所以,如果简化的话,我的单身人士看起来像这样:
经理.m
@implementation Manager
+ (instancetype)sharedManager {
__strong static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
@end
那么问题是,Interface Builder 是否可以采用它来仍然与 ARC 一起使用?
当然,我知道在没有 ARC 的情况下重写该类可能会更简单,所以这个问题相当学术性。 :)
当笔尖取消归档时,它会尝试alloc
/init
or alloc
/initWithCoder:
该类的一个新实例。
因此,您可以做的是拦截该调用并重新路由它以返回您的单例:
+ (id)sharedInstance {
static Singleton *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self actualAlloc] actualInit];
});
return sharedInstance;
}
+ (id)actualAlloc {
return [super alloc];
}
+ (id)alloc {
return [Singleton sharedInstance];
}
- (id)actualInit {
self = [super init];
if (self) {
// singleton setup...
}
return self;
}
- (id)init {
return self;
}
- (id)initWithCoder:(NSCoder *)decoder {
return self;
}
这允许-init
and -initWithCoder:
在同一个对象上安全地多次调用。通常不建议允许这样做,但考虑到单身人士已经是“事情变得非常不稳定的地方”的情况,这并不是你能做的最糟糕的事情。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)