views:

23

answers:

1

I'm trying to implement a category of an existing class. There is a static variable in the existing 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 ?

+1  A: 

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.

jlehr
thanks, so I need to subclass or add the methods to the existing class for my needs.
LeonS
Not sure I followed that. Your original question seemed to be about visibility of static variables; am I misreading that? You can also add class methods in a category, if that's what you're asking. Class and instance methods, as well as C functions, can generally access static variables as long as they're in scope. There's really nothing special about that.
jlehr