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?
That’s a class extension. You can use it to make declarations that you don’t want to be in the
.hfile.This was used by many developers, even before, who manually added the extension in the
.mfile. So I guess Apple included this in the template because it is widely used and is considered a good practice.In fact, the
.hfile 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.mfile. For those declarations, it is better to make them in the class extension.So to answer your questions:
No, it is not required but is a best practice.
Even if this was a commonly used practice, it was not included in the template.
No. The class extension doesn’t replace the
.hfile where you have to declare the “public” interface of your class.You should put in the class extension all the declarations that don’t need to be visible outside of the
.mfile.