I gather that in Objective-C I must declare instance variables as part of the interface of my class even if these variables are implementation details and have private access.

In "subjective" C, I can declare a variable in my .c file and it is not visible outside of that compilation unit. I can declare it in the corresponding .h file, and then anyone who links in that compilation unit can see the variable.

I wonder if there is an equivalent choice in Objective-C, or if I must indeed declare every ivar in the .h for my class.


Was it helpful?



A good reference to how to accomplish "invisible" instance variable declarations can be found here with credit respectfully given to Matt Gallagher.

Hope it helps, Frank


The instance variables have traditionally been needed to determine the size of the class. It's always been poor practice to directly access the ivars, and that isn't the point. In the modern runtime, this is less necessary, but at any rate, it isn't an abstraction leak unless clients are relying on the class's ivars, which should be impossible since you're declaring them as @protected or @private, right?

To restrict access, you can use the @private or @protected keywords:

@interface Foo : NSObject {
    int barPrivate;

    int barProtected;

    int barPublic;

EDIT: Scratch everything, turns out I really need some sleep.

ivars are @protected by default (although @private and @protected don't guarantee that other classes can't access them--you can always access ivars with getValue:forKey:). You should never directly access ivars from other classes directly in any case--the "choice" is whether or not to expose the ivars as properties (you just have to rely on all classes following the convention to not access ivars directly).

In the new objective-c runtime, you don't have to declare ivars at all, since they can be synthesized at runtime, but unfortunately that doesn't work with the iPhone simulator, so for now, it's best just to declare all the ivars in the .h file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow