j2emanue j2emanue - 1 month ago 8
Objective-C Question

Objective-C class extensions vs private method or variable

Im not understanding why people use extensions to make variables private instead of just declaring them only in the implementation file ?

Take a look at this code one using extension and one using a instance variable:

//this is an extension
@interface MyClass () {
NSString *myInstanceVariable;
}
// ...
@end
or in the class implementation:

@implementation MyClass {
NSString *myInstanceVariable;
}
// ...
@end


both give me instance variables that would be private. Why would i choose a extension instead of the 2nd approach of just declaring a instance variable ?

Answer

If you are declaring variables in an @interface, it exposes details of the implementation to users of the class.

If you are declaring variables in an @implementation it keeps their existence private and is not visible to someone who only imports the h file.

Edit: For more concise answer. See here