How to ensure that my singleton object doesn't get released by mistakes when multiple developers are working on the project? Can we handle it my program?
Asked
Active
Viewed 187 times
2 Answers
3
According to Apple's docs on 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;
}
You might also want to read the answers in: What should my Objective-C singleton look like?

Community
- 1
- 1

Regexident
- 29,441
- 10
- 93
- 100
1
For the time being do this, it will ensure that the singleton doesn't get released:
// 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;
}

Lokus001
- 159
- 1
- 5

Stefan Ticu
- 2,093
- 1
- 12
- 21