Please consider subscribing to Mobile Developer Tips RSS feed or following us on Twitter
|
|
|
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.
Related posts:
- Debugging with GDB: Print-Object and UIView recursiveDescription
- Class Variables
- Alert with TextFields
- Private Methods
- Java Developer’s Guide to Static variables in Objective-C
Comments
4 Responses to “Instance Variables in the Implementation File”
Leave Comment
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;
……
[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.)
[Reply]
Rafael Winter Reply:
March 5th, 2012 at 5:51 pm
The problem with private category methods and iVars is that they will not be accessible by subclasses. Like Michelle suspected.
[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.
[Reply]