-1

正如我们所知,通常我们用来在类头文件(.h)中声明我们的类实例变量,属性,方法声明。何时在类别.m文件或​​头文件中声明某些内容?

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

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

问候, Mrunal

新编辑:

大家好,

如果你是指新加入苹果的例子在developer.apple.com - 他们现在宣布他们IBOutlets和.m文件中的IBActions文件本身以及属性声明。但是我们可以通过在类私有成员部分的.h文件中声明这些引用来实现同样的功能。

那么他们为什么要在.m文件中声明那些属性和任何想法呢?

-Mrunal

+0

http://cupsofcocoa.com/2011/03/27/objective-c-lesson-8-categories/ – nsgulliver 2013-02-28 11:24:22

+0

http://stackoverflow.com/questions/3967187/difference-between-interface-definition -in-h-and-m-file – trojanfoe 2013-02-28 11:25:50

+0

应该研究objective-c中的私有和公共变量 – 2013-02-28 11:27:39

回答

1

But we can do the same things, in .m file, using blank category.

类延续。

通常情况下,您选择在标头中声明某些内容,如果它打算公开 - 任何客户端使用。其他一切(你的内部)通常应该继续上课。

我赞成封装 - 这里是我的方法:

variables

所属的类继续或@implementation。例外情况非常非常罕见。

properties

通常属于课堂上继续在实践中。如果你想让子类能够重写这些或者使这些成为公共接口的一部分,那么你可以在类声明(头文件)中声明它们。

method declarations

更多的是在类继续比在类声明中。同样,如果它意味着被任何客户使用,它将属于类声明。通常,你甚至不需要在类继续(或类声明)中声明 - 如果它是私有的,单独定义就足够了。

0

这主要取决于你。

.h文件就像你的班级的描述。
只有在.h文件中,从课堂外可以看到真正重要的东西,特别是在与其他开发人员一起工作的时候。

这将帮助他们更容易地理解他们可以使用的方法/属性/变量,而不是拥有他们不需要的全部列表。

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 

现在你可以使用“com_APX_objectAtInde声明的方法申报类别x:“方法,只要导入了”APXSafeArray.h“。

#import "APXSafeArray.h" 

... 

@property (nonatomic, strong) APXSafeArray *entities; 

- (void)didRequestEntityAtIndex:(NSInteger)anIndex 
{ 
    APXEntity *theREquestedEntity = [self.entities com_APX_objectAtIndex:anIndex]; 
    ... 
} 
相关问题