Instance Variables in the Implementation File

Within Xcode, if you set the compiler option to Apple LLVM compiler 2.1 (or greater), you can move your instance variable declarations from the interface file to the implementation file.

For example, here is a traditional interface definition with instance variables declared:

@interface SandboxViewController : UIViewController <UITextFieldDelegate>
  UITextField *username;
  UIButton    *testButton;
  UILabel     *label;

However, you can now move those same definitions to the implementation file:

@implementation SandboxViewController
  UITextField  *username;
  UIButton     *testButton;
  UILabel      *label;

The interface file would now look as follows:

@interface SandboxViewController : UIViewController <UITextFieldDelegate>

This is a nice change, as you can now have the instance variables in the implementation, where they are actually used, and only expose what is public in the interface file.

  1. Absolutely agree that private variables do not have to be in the interface file. It just mess with the idea that a .h is the public view where implementors can have a look

    Our habbits is to use anonymous category on top of the implementation to add private properties
    The pro of this approach is that we get our getter setter while staying within the .h

    Do you see any cons?

    @interface SandboxViewController()
    @property(retain) username;
    @property(retain) testButton;
    @property(retain) label;

    @implementation SandboxViewController
    @synthesize username = _username;
    @synthesize testButton = _testButton;
    @synthesize label = _label;

  2. What if the instance variable is used directly by a subclass instead of being accessed through a property? Will the subclass compile? (Will check it myself later today but nice to have as part of the public record.)

    • The problem with private category methods and iVars is that they will not be accessible by subclasses. Like Michelle suspected.

  3. Unless I’m mistaken, I think the overall point of private ivars is to hide the fact that they exist. It’s probably just a matter of preference, more than anything else. But I’ve had many an occasion where I’ve not wanted an ivar to be declared in the header file, simply because I don’t want the fact of its existence known to people who might be scanning the header at a later point.

    I only want people to know about the things I want them to know about. Paranoid? Perhaps.

    • I copy that! Not paranoid at all… more the opposite of it.
      Keeping the instance variables privat let me stay sane ;-)

Comments are closed.