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

objective c - Why is there @interface above @implementation?

I am wondering why there is twice @interface. One in class.h and other in class.m. For example:

TestTableViewController.h:

#import <UIKit/UIKit.h>

@interface TestTableViewController : UITableViewController

@end

and (automatically generated) class.m i find:

#import "TestTableViewController.h"

@interface TestTableViewController ()

@end

@implementation TestTableViewController

... methods delegated from UITable delegates

@end

So my question is, what the @interface TestTableViewController () in the .m file is about. Why it is there? Do I need it?

Thanks in advance

question from:https://stackoverflow.com/questions/11594391/why-is-there-interface-above-implementation

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

1 Reply

0 votes
by (71.8m points)

The second @interface directive is in the implementation file (.m) -- you can infer from it that it's meant for declaring stuff that the creator of the class didn't want to expose to the user of the class. This usually means private and/or internal methods and properties. Also note that there are two types of doing this. The one (which you see here) is called a "class extension" and it's denoted by an empty pair of parentheses:

@interface MyClass ()

This one is particularily important because you can use this to add additional instance variables to your class.

The second one, called a "category", is indicated by a non-empty pair of parentheses, enclosing the name of the category, like this:

@interface MyClass (CategoryName)

and it's also used to extend the class. You can't add instance variables to a class using categories, but you can have multiple categories for the same class, that's the reason why it's mainly used to extend system/framework classes for which you don't have the source code -- so a category, in this sense, is the exact opposite of the class extension.


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

...