Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between adding pseudo-private ivars in a class extension or in the @implementation block?

What's the difference between putting pseudo-private instance variables in a class extension inside the .m file, or putting them in the newly introduced @implementation brackets like shown below?

Are there consequences, pros, cons over one or the other way? Is internal2 treated differently than internal3 in a way a programmer must care of? (of course there is a difference McKay would say but the question is if you care in practice or not).

// MyClass.m

@interface MyClass () {
    id internal2;
}
@end


@implementation MyClass {
    id internal3;
}

- (void)internalMethod {
    NSLog(@"%@ %@", internal2, internal3);
}

@end

source: http://www.mcubedsw.com/blog/index.php/site/comments/new_objective-c_features/

like image 905
Proud Member Avatar asked Feb 03 '12 01:02

Proud Member


2 Answers

The main difference between the two approaches is that you can include the class extension in a separate header, whereas the @implementation ivars obviously have to go with the @implementation block in the .m file (and there can only be one @implementation for a given class (extensions not included)). The practical result of this is that you can have multiple levels of "private" ivars:

  • MyClass.h: public ivars
  • MyClass+Private.h: semi-private ivars
  • MyClass.m: really private ivars

As a hypothetical example, pretend that MyClass is UIView. In that case, UIView.h is the header that we can all access, UIView+Private.h is the "private" header than only Apple can access, and UIView.m has stuff that only the people specifically responsible for UIView need to know about.

like image 107
UIAdam Avatar answered Sep 28 '22 08:09

UIAdam


Personally, I prefer to put my ivars in a single class extension in the implementation file, I think it's cleaner that way. I don't think there are any performance advantages or consequences to using one or the other, it's more about being able to code the way you want to.

like image 39
Ell Neal Avatar answered Sep 28 '22 07:09

Ell Neal