开发者

Objective-C Modifers for static?

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 开发者_C百科my header file?


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.


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜