Access static variables in ObjC categories
I'm trying to implement a category of an existing class. There is a static variable in the existi开发者_开发技巧ng class. If I try to access the static variable from a category, I'm getting an error that the static variable is undeclared.
Is it possible to access static variables in ObjC Categories ?
Just to be clear, Objective-C doesn't associate static variables with classes. Static variables are simply scoped by default to whatever file they're declared in.
To make a static variable visible in other files, add a declaration in the corresponding header file prefixed with the keyword extern
. So for example, if you had defined the following static variable somewhere in one of your .m files
int seconds = 60;
you could then add the following declaration in the .h file:
extern int seconds;
Then, any .m file that imports that .h file will see the static variable.
精彩评论