1

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;
    }
Community
  • 1
  • 1
stevebot
  • 23,275
  • 29
  • 119
  • 181

3 Answers3

4

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.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
4

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.

John Topley
  • 113,588
  • 46
  • 195
  • 237
  • awesome succinct answer. I assume that using a static local variable is a means of defensive coding so that only the function can alter the variable as opposed to a class field? – stevebot Oct 21 '14 at 15:42
  • 1
    @stevebot I would more say that you want to limit the scope of your variables to be as restrictive as possible (to avoid side unwanted effects). There's no need to make `sharedInstance` and `onceToken` class fields and doing so would needlessly pollute the class because they're only relevant to the `sharedInstance` method. – John Topley Oct 21 '14 at 15:46
-1

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

ZAZ
  • 597
  • 3
  • 6