0

In my UITableViewCell subclass, I have the following code:

-(void)updateConstraints
{   
    static dispatch_once_t once;
    dispatch_once(&once, ^ {
    // Set constraints here
    });

    [super updateConstraints];
}

The constraints are only set for the first instance of the custom cell class. I don't really understand what's happening with the static token. I was under the impression that it is an instance-specific variable, but apparently it is class-scoped. Can anyone explain this?

jscs
  • 63,694
  • 13
  • 151
  • 195
GoldenJoe
  • 7,874
  • 7
  • 53
  • 92

1 Answers1

1

The variable once is neither a instance variable, nor a static class variable.

It's a static variable with scope local to the updateConstraints method. It's visible only within that method, gets created the first time updateConstraints is called, and has a lifetime that extends through the end of the program. In other words, once keeps its value between calls to updateConstraints.

The dispatch_once function uses this fact to ensure the block gets run exactly once.

godel9
  • 7,340
  • 1
  • 33
  • 53
  • Then why can I have that block of code in two different classes, and it will run once for each class? – GoldenJoe Nov 16 '13 at 21:06
  • It's because they're two different methods. I'll use C++ syntax, since I don't know of a quick way of expressing this idea in Objective C. If you have two classes, ClassA and ClassB, then `ClassA::updateConstraints` and `ClassB::updateConstraints` are not the same function. – godel9 Nov 16 '13 at 21:12
  • I see...so you can have static variables that are tied to functions. I only thought variables could belong to classes or objects. Thanks for the insight. – GoldenJoe Nov 16 '13 at 21:16