Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

objective c - 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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...