-1

众所周知,通常我们习惯于在类头文件(.h)中声明我们的类实例变量、属性、方法声明。

但是我们可以在 .m 文件中使用空白类别做同样的事情。

所以我的问题是:什么应该在 .h 文件中声明,什么应该在 .m 文件中声明 - 为什么?

问候, Mrunal

新编辑:

大家好,

如果您在 developer.apple.com 上参考新添加的 Apple 示例 - 他们现在在 .m 文件本身中声明他们的 IBOutlets 和 IBActions 以及属性声明。但是我们可以通过在类私有成员部分的 .h 文件中声明这些引用来实现相同的目的。

那他们为什么要在 .m 文件中声明它们并作为属性,知道吗?

-Mrunal

4

4 回答 4

2

但是我们可以在 .m 文件中使用空白类别做同样的事情。

继续上课。

通常,如果要公开,您选择在标头中声明某些内容——任何客户端都可以使用它。其他所有内容(您的内部结构)通常都应该在课程延续中进行。

我赞成封装——这是我的方法:

变量

属于类延续或@implementation。例外非常非常罕见。

特性

通常属于实践中的类延续。如果您想让子类能够覆盖这些或使这些成为公共接口的一部分,那么您可以在类声明(头文件)中声明它们。

方法声明

在类延续中比在类声明中更多。同样,如果它打算被任何客户端使用,它将属于类声明。通常,您甚至不需要在类延续(或类声明)中声明——如果它是私有的,那么单独定义就足够了。

于 2013-02-28T11:51:01.687 回答
1

基本上,在头文件 (.h) 中声明公共 API,而在实现文件 (.m) 中声明私有 API。

Objective-C 中的可见性

你也可以在这里找到答案

于 2013-02-28T11:42:05.730 回答
0

通常您希望在 .m 文件中使用空白类别来声明私有属性。

// APXCustomButton.m file
@interface APXCustomButton ()

@property (nonatomic, strong) UIColor *stateBackgroundColor;

@end

// Use the property in implementation (the same .m file)
@implementation APXCustomButton

- (void)setStyle:(APXButtonStyle)aStyle
{
    UIColor *theStyleColor = ...;
    self.stateBackgroundColor = theStyleColor;
}

@end

如果您尝试访问在 .m 文件之外的黑色类别中声明的属性,您将收到未声明的属性编译器错误:

- (void)createButton
{
    APXCustomButton *theCustomButton = [[APXCustomButton alloc] init];
    theCustomButton.stateBackgroundColor = [UIColor greenColor]; // undeclared property error
}

在大多数情况下,如果您想在没有子类化的情况下向现有类添加新方法/属性,那么您需要在 .h 文件中声明类别并在 .m 文件中实现声明的方法

// APXSafeArray.h file
@interface NSArray (APXSafeArray)

- (id)com_APX_objectAtIndex:(NSInteger)anIndex;

@end

// APXSafeArray.m file
@implementation NSArray

- (id)com_APX_objectAtIndex:(NSInteger)anIndex
{
    id theResultObject = nil;
    if ((anIndex >= 0) && (anIndex < [self count]))
    {
        theResultObject = [self objectAtIndex:anIndex];
    }

    return theResultObject;
}

@end

现在,您可以在导入“APXSafeArray.h”的任何地方使用“com_APX_objectAtIndex:”方法。

#import "APXSafeArray.h"

...

@property (nonatomic, strong) APXSafeArray *entities;

- (void)didRequestEntityAtIndex:(NSInteger)anIndex
{
    APXEntity *theREquestedEntity = [self.entities com_APX_objectAtIndex:anIndex];
    ...
}
于 2013-02-28T11:53:57.190 回答
0

这主要取决于你。

.h文件就像您的课程的描述。
只在.h文件中放入从类外部可见的真正重要的内容是明智的,尤其是在您与其他开发人员一起工作时。

它将帮助他们更容易地理解他们可以使用哪些方法/属性/变量,而不是列出他们不使用的东西的完整列表。

于 2013-02-28T11:34:08.117 回答