各种@interface 声明,有些带有括号 [英] Varieties of @interface declarations, some with parentheses
问题描述
我注意到 Objective-c 类的各种 @interface
声明.我想了解为什么开发人员通过以下方式声明 @interface
:
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
推荐答案
这只是一个普通的类接口,继承自NSObject,在其中声明ivars、属性和方法
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
以下两个是categories,它允许您向类添加方法.但是,它不是子类(不要声明具有相同名称的方法,因为您将无法访问原始方法).如果您有接口的命名类别(如 @interface MyClass (Private)
),则应在 @implementation MyClass (Private)
中提供实现,在这种情况下对于未命名的类别(也称为扩展),可以照常提供实现.请注意,扩展还允许您将 ivars 添加到类中,而(命名)类别则不允许.
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
这篇关于各种@interface 声明,有些带有括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!