armnotstrong
armnotstrong

Reputation: 9065

Why this objective-c singleton works?

I have create a singleton of Objective-C like this as find on the internet tutorial:

+(id) sharedInstance{
    static AdManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

Will the static AdManager *manager be released once the holder be released? and since the *manager is defined in a method scope rather than a field variable, will it be released too?

Then where will the object be held so it could be used next time we call sharedInstance?

Upvotes: 0

Views: 24

Answers (1)

CRD
CRD

Reputation: 53000

A variable declared as static within a method or function has global lifetime, but it is only visible by name within its declaring method/function.

As manager is a strong variable (by default) any object referenced by it will be owned by this variable either until the program terminates or a different reference (or nil) is assigned to manager.

HTH

Upvotes: 2

Related Questions