Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add ivars in @implementation

Tags:

objective-c

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?

like image 216
an0 Avatar asked Jan 13 '12 16:01

an0


2 Answers

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

  • https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW6

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

like image 136
mattjgalloway Avatar answered Nov 08 '22 15:11

mattjgalloway


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
like image 34
jowie Avatar answered Nov 08 '22 15:11

jowie