5

What's the convention/rule/preference/diktat about where private instance variables should be declared and why?

// someClass.h

@interface someClass : NSObject {
@private
// Here in the class declaration?
}
// ...
@end

// someClass.m

@interface someClass () {
// Here in the class extension? This seems to be obj-c's version
// of the C++ Pimpl idiom.
}
@end

@implementation someClass {
// Here in the class definition? BTW, what's the default scope here?
// Seems like it should be @private. I haven't been able to find much
// documentation about this declaration block.
}
// ...
@end

Can anyone comment on the appropriate use of these three sections or point to a good web resource on this? Thanks!

Phil
  • 1,030
  • 1
  • 16
  • 22
  • The title's a bit cheeky but I'm serious about the question. I haven't been able to find thorough documentation on this topic. Nothing I've seen from books (Kochan, Sadun, Ali) and Apple doc gives a thorough and comprehensive discussion about it. – Phil Mar 04 '13 at 22:46
  • 2
    The default scope of ivars in the `@implementation` block is `@private`. However this is almost certainly irrelevant, because unless you're putting multiple classes in the same `.m` file, no other classes can even *see* the ivars, which is a prerequisite to attempting to access them. – Lily Ballard Mar 04 '13 at 22:52
  • Rob, the link you mention does answer my question. All the contributors here have helped clarify this topic for me. If I could I would put a check on both yours and Nikolai's answers. – Phil Mar 04 '13 at 23:02

1 Answers1

4

Today it's best practice to put them in the @implementation or in a (non-public) class extension.

Ivars are never of interest to clients of a class, so they should not be visible in the public API (the header).

There's not much difference in putting them in the @implementation or in a class-extension. For consistence I always put them in the @implementation.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • for consistence I always put them into a class extension. – vikingosegundo Mar 04 '13 at 22:52
  • A follow-up question if I may: what would you advocate for classes that want to expose instance variables to subclasses? Personally I tend to prefer a category with appropriate getters and possibly declared elsewhere than in the main 'public' header. – Tommy Mar 04 '13 at 22:54
  • @Tommy I consider this breaking the encapsulation. Other classes (subclass or not) never should access ivars. – Nikolai Ruhe Mar 04 '13 at 22:55