What is the empty @interface declaration in .m files used for?
Asked Answered
B

2

46

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?
Boykins answered 17/3, 2012 at 15:8 Comment(1)
possible duplicate of Difference between @interface definition in .h and .m fileSterne
E
78

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.

Ejector answered 17/3, 2012 at 15:12 Comment(1)
Thanks for such a thorough answer! Glad to see apple include this in the new template as it's a best practice that most developers are implementing anyway!Boykins
T
11

The interface section in the implementation file allows you to declare variables, properties, and methods that are private, meaning that they won't be seen by other classes.

No, it's not required at all. But I use it as much as possible and only make public those things that other classes need to see.

Theatricalize answered 17/3, 2012 at 15:15 Comment(1)
Private in the sense that the compiler doesn't see the variables, properties and methods form outside the class, but as we are using Objective-C methods are not really private anyway as anyone can call anything...Aretino

© 2022 - 2024 — McMap. All rights reserved.