an0
an0

Reputation: 17530

Add ivars in @implementation

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?

Upvotes: 11

Views: 1767

Answers (2)

jowie
jowie

Reputation: 8068

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

Upvotes: 3

mattjgalloway
mattjgalloway

Reputation: 34912

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.

Upvotes: 11

Related Questions