Instance Variables in the Implementation File

March 5, 2012

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;
}
@end

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>
@end

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.

5 comments

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;
@end

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

by pierre on Mar 5, 2012. Reply #

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.)

by Michelle on Mar 5, 2012. Reply #

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

by Rafael Winter on Mar 5, 2012. Reply #

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.

by Gregory Hill on Mar 6, 2012. Reply #

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

by Karsten on Jun 12, 2012. Reply #

Leave a Comment