0

Lately, it seems that explicitly declared instance variables in Objective-C are considered a thing to avoid, with the preference being to use "private" properties, i.e., properties declared in a class extension in the .m file.

The last example of this is the WWDC '12 presentation on advances in Objective-C.

What I haven't been able to find is a rationale for this preference, and I have searched a lot. It obviously provides a sort of solution to the fragile base class problem, but that was already solved with Objective-C 2.

Is there some crucial piece of documentation that I have missed, or is there a simple explanation that a kind soul could provide here?

Monolo
  • 18,205
  • 17
  • 69
  • 103
  • You should ask this on the Apple Developer Forums as not many people have access to the WWDC '12 videos and you *may* even get an answer from the presenter of that session. – trojanfoe Jun 27 '12 at 12:59

1 Answers1

2

You mean this?

@interface Foo : NSObject {
    float bar;
    id baz;
}

If those instance variables are not a part of the public interface, you will do better to move them into the implementation file, either as declared properties in a class extension or to the @implementation block:

@interface Foo ()
@property(assign) float bar;
@property(strong) id baz;
@end

…or:

@implementation Foo {
    float bar;
    id baz;
}

This way the public interface declared in the header stays simple and changes in the implementation won’t force a recompilation of all the source files that import the header.

zoul
  • 102,279
  • 44
  • 260
  • 354
  • Actually, I was referring to those suggestions of avoiding the (explicitly declared) instance variables altogether. While I see that it is possible with the latest developments in LLVM, I have not grasped the rationale behind the thinking, hence the question. – Monolo Jun 27 '12 at 13:16
  • There are two things in play. Properties declared using `@property` and instance variables declared in the `@interface {…}` block. It used to be that you had to declare an instance variable for each property to hold its value. Nowadays that’s no longer necessary, since the compiler will synthesize an instance variable for the property automatically. And if you don’t have a public property declared for an instance variable, it’s really a *private* instance variable and belongs in the implementation file. So yes, there is no need to have any instance variables in the header file. – zoul Jun 27 '12 at 13:38
  • And if you are talking about dropping the instance variables even from the implementation file, I don’t think there are strong reasons for that. You can use declared properties instead (see my second code block in the answer), it could be said that they make the memory management rules more apparent (strong, weak, assign, …) and offer a cleaner interface to subclasses, which can no longer misuse your instance variables directly and have to go through the accessor. – zoul Jun 27 '12 at 13:59