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

objective c - Varieties of @interface declarations, some with parentheses

I've noticed a variety of @interface declarations for Objective-c classes. I'd like to understand why developers declare @interface in the following ways:

// in the .h file
@interface MyClass : NSObject
// ...
@end

// in the .m file (what's the purpose of the parens?)
@interface MyClass ()
// more property declarations which seem like they can go in the .h file
@end

// again in the .m file (what's the purpose of private?)
@interface MyClass (Private)
// some method declarations
@end
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is just a normal class interface, inheriting from NSObject, where you declare ivars, properties and methods

// in the .h file
@interface MyClass : NSObject
// ...
@end

The following two are categories, which allow you to add methods to a class. It is not a subclass however (do not declare a method with the same name, as you won't be able to access the original one). If you have a named category of the interface (like @interface MyClass (Private)), then the implementation should be provided in @implementation MyClass (Private), in the case of unnamed categories (also called extensions), the implementation can be provided as usual. Note that extensions also allow you to add ivars to the class while (named) categories do not.

// in the .m file (what's the purpose of the parens?)
@interface MyClass ()
// more property declarations which seem like they can go in the .h file
@end

// again in the .m file (what's the purpose of private?)
@interface MyClass (Private)
// some method declarations
@end

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

...