12

Is there any difference between declaring a private instance variable in the header vs declaring it in the implementation?

in TestObj.h

@interface TestObj : NSObject
{
    int test;
}
@end

vs in TestObj.m

@interface TestObj()
{
    int test;
}
@end

Both seem equivalent to me, is there any actual difference between declaring an instance variable in the header vs in the implementation, if not which is preferred? The @interface within the implementation file just seems like a way to declare private properties, does it have any other purpose outside that?

Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138

2 Answers2

15

The preference is generally to place private instance variables and properties in the private class extension (in the .m) and leave the public interface file (.h) for those properties and methods that are truly part of the public interface.

It helps isolate implementation details from the public interface and makes everything much cleaner. It also ensures that external classes do not inadvertently alter the private variables of this class.

See Class Extensions Extend the Internal Implementation.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • So to clarify besides organization there is no functional difference between the two? – Kevin DiTraglia Sep 04 '13 at 14:50
  • @KevinDiTraglia Correct, no functional difference within the `TestObj` class, but ensures that external classes do not inadvertently mess around with private variables. That strikes me as more than just an "organizational" detail, but rather critical in making robust code. – Rob Sep 04 '13 at 14:54
  • 7
    There is one functional difference: ivars in the class's `@interface` are `@protected` by default, and ivars in a class extension `@interface` or in `@implementation` are `@private` by default. – Greg Parker Sep 04 '13 at 18:02
7

Greg Parker's comment on the accepted answer is the best answer here:

There is one functional difference: ivars in the class's @interface are @protected by default, and ivars in a class extension @interface or in @implementation are @private by default.

acannon828
  • 528
  • 7
  • 22
  • So say you are making an SDK with a private class extension in its own TestObj_Private.h, you would then need to declare the ivar as @protected ? – malhal Aug 04 '16 at 13:02