Recently I came across the question NSString: Why use static over literal? and in the comments arrived a new question.

In Objective-C there some "special" types that are just maps to C primitives. Like the NSInteger.

typedef long NSInteger;
typedef int NSInteger;

I know how to use the static keywords for objects but I don't understand the implications on C primitive types.

When should I use a static NSInteger x instead of NSInteger x? What happens with the memory in both cases?

  • Non-static variables are on the stack, static variables aren't.
    – user4595
    Commented Nov 25, 2011 at 23:30
  • 1
    This question has been answered so many times on stackoverflow.com...
    – user29079
    Commented Nov 28, 2011 at 7:32

1 Answer 1


The static key word can have three meanings as it related to primitives

  1. Declared inside a function. You could think of this as essentially creating a cache that only has scope in the function. The variable is only initialized once the first time the that function is called. The variable retains the same state it had from the previous call on all subsequent calls to the function. None static variables are put on the stack and have lifetime equivalent to duration of the function. The memory for static variables is someplace else and it always exists similarly to a global variable. In practice, I hardly see this used and personally, I don't think that I have ever used this outside of debugging.
  2. Declared in global scope. Using a static variable in global scope simply limits the scope of the variable to the file it was declared in. It is a global variable, but it is only accessible from the scope/file that it was declared in. I use this all the time. It is certainly good practice from a data encapsulation standpoint, but it also helps limit possible namespace collisions. There is no difference in memory usage.
  3. Declared in Class. This is similar to the first example. For each static variable in a class there is exactly one "copy" regardless of how many Class objects have been instantiated. It is sort of like a global variable that all instantiated objects of that type share.
  • I see the first case being used in UIKit to create new UITableViewCells to store the reuseIdentifier. Commented Nov 30, 2011 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.