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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With