starkshang
starkshang

Reputation: 8558

Why Xcode generates "unnecessary" code when create class?

When I want to create an CocoaTouch class with Xcode,and it generates an .h and .m file,what's confused me is why .m file have such code:

#import "MealTableViewController.h"
//**************below looks unnecessary
@interface MealTableViewController ()

@end
//**************above looks unnecessary
@implementation MealTableViewController

@end

In my opinion,it looks like unnecessary because I have declared this class implements MealTableViewController.h,and even I delete it,the result will be same as before.So why this code will be generated automatically?What's the purpose of creating it? Anyone knows please teach me,thanks!

Upvotes: 1

Views: 49

Answers (2)

DarkDust
DarkDust

Reputation: 92384

In ancient times, the Objective-C compiler needed to know the method names and signatures by the time the method was actually used. So if your class defined a method - (void)foo:(NSString *)bar; then the compiler must know about this before you could actually call [self foo:@"bing"];. You can't always "sort" your methods in such a way that methods are always defined before use (for example, if you have method alpha and method beta but both call each other). If you don't want to expose your internal methods in your .h file, you had to declare them in a class extension or category.

Nowadays, the Objective-C compiler is smart enough so it doesn't need this workaround any more. But if you want to declare properties that shouldn't be exposed in the .h file, you still need to do so in a class extension. That's why the default empty templates still adds an extension.

Upvotes: 2

nsinvocation
nsinvocation

Reputation: 7637

@interface inside your .m file means you can declare here some private properties/methods

Upvotes: 0

Related Questions