当多个开发人员正在处理项目时,如何确保我的单例对象不会被错误释放?我们可以处理它的程序吗?
答案 0 :(得分:3)
根据Apple关于Creating a Singleton Instance的文档:
static MyGizmoClass *sharedGizmoManager = nil;
+ (MyGizmoClass*)sharedManager
{
if (sharedGizmoManager == nil) {
sharedGizmoManager = [[super allocWithZone:NULL] init];
}
return sharedGizmoManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [[self sharedManager] retain];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (NSUInteger)retainCount
{
return NSUIntegerMax;
}
- (oneway void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
您可能还想阅读以下内容中的答案:What should my Objective-C singleton look like?
答案 1 :(得分:1)
暂时这样做,它将确保单身人士不会被释放:
// This function is empty, as we don't want to let the user release this object.
- (oneway void)release {
}
//Do nothing, other than return the shared instance - as this is expected from autorelease.
- (id)autorelease {
return self;
}