Horray
Horray

Reputation: 693

Singleton in Objective C

What does the following method actually do?

(This is created in an NSObject class.)

+ (MyClass *)sharedInstance
{
    static MyClass *sharedInstance;

    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] init];
    });

    return sharedInstance;
}
- (NSArray *)myArray {
    ....
}

Then in another class I would call myArray like this:

[[MyClass sharedInstance] myArray];

Does sharedInstance get called every time the above code gets executed? Also, how can I call myArray without initializing it first? (Note myArray is - not +)

Upvotes: 0

Views: 39

Answers (1)

Ben
Ben

Reputation: 186

It's the regular implementation of the Singleton pattern. You have a static reference to a single instance of MyClass, allocated when you first call +sharedInstance.

+sharedInstance will indeed get called every time [MyClass sharedInstance] is executed, but that shouldn't be a problem. You also shouldn't need to call -myArray without using the singleton. You could do it by just allocating a local instance and call -myArray on it.

Upvotes: 1

Related Questions