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
507 views
in Technique[技术] by (71.8m points)

objective c - What is the empty @interface declaration in .m files used for?

I've started a new iOS 5 project and noticed something new at the top of each .m file

#import "HomeViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController
@synthesize ...
  • Is this extra @interface ... required if I have a separate .h file?
  • Why did this not show up in pre iOS 5 projects?
  • Can I use this instead of having a separate .h file?
  • What is the best practice for this going forward?
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

That's a class extension. You can use it to make declarations that you don't want to be in the .h file.

This was used by many developers, even before, who manually added the extension in the .m file. So I guess Apple included this in the template because it is widely used and is considered a good practice.

In fact, the .h file should only be used to make declarations that are going to be used from other files. You may have to declare some properties, methods or constants that will only be used inside the .m file. For those declarations, it is better to make them in the class extension.

So to answer your questions:

  • Is this extra @interface ... required if I have a separate .h file?

No, it is not required but is a best practice.

  • Why did this not show up in pre iOS 5 projects?

Even if this was a commonly used practice, it was not included in the template.

  • Can I use this instead of having a separate .h file?

No. The class extension doesn't replace the .h file where you have to declare the "public" interface of your class.

  • What is the best practice for this going forward?

You should put in the class extension all the declarations that don't need to be visible outside of the .m file.


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

...