0

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?

Jon
  • 428,835
  • 81
  • 738
  • 806
Prabh
  • 2,466
  • 2
  • 24
  • 27

2 Answers2

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