3

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 ?

rmaddy
  • 307,833
  • 40
  • 508
  • 550
j2emanue
  • 56,631
  • 57
  • 264
  • 415
  • 1
    I never use a class extension for private variables. It's a lot more typing if all you want are private ivars. I only use the class extension to add private properties or declare privately that my class conforms to one or more protocols. – rmaddy Mar 25 '15 at 18:46
  • I think this is what you are looking for (or at least can be helpful): http://stackoverflow.com/a/13573236/3402095 – Whirlwind Mar 25 '15 at 18:56
  • [Use class extension for selective visibility in ObjC](http://stackoverflow.com/q/7110525) – jscs Mar 25 '15 at 19:19

1 Answers1

-1

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

Community
  • 1
  • 1
Anish Parajuli 웃
  • 18,729
  • 9
  • 55
  • 70
  • 3
    How does this answer the question? This makes no attempt to answer why to use one or the other approach. – rmaddy Mar 25 '15 at 18:44