-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]; 
    ... 
}