3

How do I create a static variable in my Objective-C class? I'm familiar with using @private in my header files for private variables, but I am trying to create a static method which accesses a static variable. How should I declare this static variable in my header file?

StanLe
  • 5,037
  • 9
  • 38
  • 41
  • 1
    possible duplicate of [Objective C Static Class Level variables](http://stackoverflow.com/questions/1063229/objective-c-static-class-level-variables) – jscs Jul 06 '11 at 19:27

3 Answers3

3

Objective-C simply follows C in this regard - you make static file variables. In your implementation (ie your .m file) put a declaration anywhere (but ideally somewhere sensible like at the top of the file, or even in the relevant method if it's only accessed in one place).

If you want to provide controlled access to such a static, put it outside of any method implementation, and use class methods to access it.

Bored Astronaut
  • 994
  • 5
  • 10
2

Static variables for Objective-C follow the same rules for static variables in C (storage modifier). You can declare your static variables at file or function scope but they have no relation to your class like instance variables do.

Joe
  • 56,979
  • 9
  • 128
  • 135
1

Objective-C doesn't have static class variables. You can create module-static variables (just as in C), however. To have a private, static variable:

//MyClass.m
static int MyStatic;

@implementation MyClass
@end

will give MyStatic module-level scope. Because this is just C, there's no way to make MyStatic visible from, e.g. categories on MyClass without making it publicly visible via an extern declaration. Since static variables are effectively global variables, this is probably a good thing—MyClass should be doing absolutely everything it can to hide the existence of MyStatic.

If you want the static variable to be public (you really don't want to):

//MyClass.h
extern int MyStatic;

@interface MyClass {}
@end

//MyClass.m
int MyStatic;

@implementation MyClass
@end
Barry Wark
  • 107,306
  • 24
  • 181
  • 206