stevebot
stevebot

Reputation: 24005

What does the static keyword mean in a class method

Having just read Why does Apple recommend to use dispatch_once for implementing the singleton pattern under ARC?, I find the answers and approach Apple recommends for singletons to be extremely cool and neat to look at, but after further thought I was left wondering, what does the static keyword inside of a class method mean exactly in objective-c? Prior to this pattern recommended by Apple, I had only encountered static as a modifier for class fields. How does the behavior change when static is used in a class method?

 + (MyClass *)sharedInstance
    {
        //  Static local predicate must be initialized to 0
        static MyClass *sharedInstance = nil;
        static dispatch_once_t onceToken = 0;
        dispatch_once(&onceToken, ^{
            sharedInstance = [[MyClass alloc] init];
            // Do any other initialisation stuff here
        });
        return sharedInstance;
    }

Upvotes: 1

Views: 750

Answers (3)

John Topley
John Topley

Reputation: 115372

In this case it's a C language construct* meaning a static local variable. Static local variables keep their memory cell throughout the program execution. In practice this means that once the variable is assigned a value it retains that value during subsequent function calls. So it acts like a cache.

You also see it used a lot in Objective-C with NSDateFormatter instances because these are expensive to create, so you only want to do it once and then reuse the same instance.

* Remember that Objective-C is a superset of C.

Upvotes: 4

gnasher729
gnasher729

Reputation: 52538

Every language seems to use "static" in a different way.

"static" in Objective-C is exactly the same as "static" in any old C program. It's a variable with the lifetime of the application, with the name accessible to the enclosing scope only. Whether this is inside an Objective-C class method, an instance method, an old C function or even outside any function.

Upvotes: 4

ZAZ
ZAZ

Reputation: 593

As per Apple Documentation, Declaring a variable static limits its scope to just the class in objective-C

Upvotes: -1

Related Questions