user2412433
user2412433

Reputation: 11

"[[self sharedManager] retain]" why should retain

In apple doc singleton:

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;  //denotes an object that cannot be released
}

- (void)release {
    //do nothing
}

- (id)autorelease {
    return self;
}

I have a question:

+ (id)allocWithZone:(NSZone *)zone {
    return [[self sharedManager] retain];
}

retain should omit, but why remain retain?

Because return [self sharedManager] or [[self sharedManager] retain] is equal.

Upvotes: 0

Views: 95

Answers (1)

jscs
jscs

Reputation: 64002

The sharedGizmoManager is owned by its own class, but any client code that tries to use allocWithZone: to create an instance will expect to own the returned reference (that's the rule for alloc/allocWithZone:). The retain does exactly that -- gives (partial) ownership to the calling code over the existing instance.

The client code, since it has an owning reference, is required to send release at some point, when it's done using the object. If there was no "extra" retain, this would actually release the ownership claim that the object has on itself, and the object could be (improperly) deallocated.

In a sentence, the retain is there to make the singleton, which is in fact managing its own lifetime, compatible with the rules that client code will be following.

Upvotes: 1

Related Questions