11

For good encapsulation, decent Objective-C programmers put their private ivars in a private extension declared in the main implementation file, like this:

// MyClass.m

@interface MyClass () {
    float value;
}
@end

@implementation MyClass
@end

But recently, I found a simpler way to hide private ivars: ivars can be declared in a {} block following @implementation, like this:

// MyClass.m

@implementation MyClass {
    float value;
}
@end

It is really handy when no private methods but only private ivars need to be hidden.

However, I'm not sure about its syntax validity. Can anyone validate or invalidate it with some canonical references?

an0
  • 17,191
  • 12
  • 86
  • 136

2 Answers2

11

It's perfectly valid and here is a document by Apple talking about it:

I don't personally use it as I prefer the syntax of a class continuation category.

mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
  • @cHao yes apple updated their link structure at some point and broke lots of old links from SO posts. Annoying to say the least. – Brynjar Apr 14 '13 at 09:24
  • Here is the updated link: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html - look for the subheading "You Can Define Instance Variables without Properties" a little way down the page. – jowie Jun 06 '13 at 09:15
3

I was also curious about this. Here is the updated link from Apple:

You Can Define Instance Variables without Properties

It’s best practice to use a property on an object any time you need to keep track of a value or another object.

If you do need to define your own instance variables without declaring a property, you can add them inside braces at the top of the class interface or implementation, like this:

@interface SomeClass : NSObject {
    NSString *_myNonPropertyInstanceVariable;
}
...
@end

@implementation SomeClass {
    NSString *_anotherCustomInstanceVariable;
}
...
@end
Community
  • 1
  • 1
jowie
  • 8,028
  • 8
  • 55
  • 94