【问题标题】:Varieties of @interface declarations, some with parentheses各种@interface 声明,有些带有括号
【发布时间】:2011-10-12 18:44:58
【问题描述】:

我注意到针对 Objective-c 类的各种 @interface 声明。我想了解为什么开发者会通过以下方式声明@interface

// 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

【问题讨论】:

标签: objective-c interface class-design


【解决方案1】:

这只是一个普通的class interface,继承自NSObject,在这里你声明了ivars、属性和方法

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

下面两个是categories,可以给类添加方法。但是,它不是子类(不要声明具有相同名称的方法,因为您将无法访问原始方法)。如果你有接口的命名类(如@interface MyClass (Private)),那么在@implementation MyClass (Private)中应该提供实现,对于未命名的类(也称为扩展),可以照常提供实现。请注意,扩展还允许您将 ivars 添加到类中,而(命名的)类别则不允许。

// 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

【讨论】:

  • 目前可以将存储添加到扩展中的类。不太可能通过类别来做到这一点。
【解决方案2】:

用于声明私有方法。

此回复详细解释了这一点:What are best practices that you use when writing Objective-C and Cocoa?

【讨论】:

    【解决方案3】:

    .m 文件中的内容是私有的。括号用于类别,因此您可以将代码分成类别以使其更具可读性。因为代码在.m 中并且是私有的,所以他们称之为私有类别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      相关资源
      最近更新 更多