views:

91

answers:

2

I've noticed that a lot of Apple's interfaces use @private before their instance variable declarations. Is there a good design reason for this, and is it something I should do?

+1  A: 

If you don't want subclasses to be able to access the variables, mark them @private.

Chuck
+3  A: 

Private instance variables are used to separate interface from implementation. In Objective-C, since the class declaration must show all of the instance variables, there needs to be a way to prevent subclasses from accessing the ones that are part of the internal implementation. Otherwise, other programmers could write code that depends on those internal variables, which would make it impossible for the class designer to make changes to the class internals without breaking existing code.

Looking at it another way, the instance variables that are not marked private are part of a contract with the subclass programmer, whereas the ones marked private are not.

This means that instance variables should usually be marked private so that they can only be accessed through their accessor methods, if at all. Otherwise, someone could easily write a subclass of your class, and simply create an accessor to make any instance variable public.

e.James
Thanks for your detailed answer. As for writing a subclass to publicize instance variables, I'm pretty sure that `@private` doesn't protect against categories publicizing them. Thoughts?
Jonathan Sterling
I tried it out, and you are absolutely correct. It seems that categories are given access to all instance variables, including the private ones. I suppose Objective-C still gives you enough rope to hang yourself with if you really want to :)
e.James
You could also still use the runtime functions to grab the ivar. But if you're doing such things, you know it's a dirty hack, unlike innocently depending on a superclass ivar that you thought was reliable.
Chuck