通常您想在.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];
...
}
http://cupsofcocoa.com/2011/03/27/objective-c-lesson-8-categories/ – nsgulliver 2013-02-28 11:24:22
http://stackoverflow.com/questions/3967187/difference-between-interface-definition -in-h-and-m-file – trojanfoe 2013-02-28 11:25:50
應該研究objective-c中的私有和公共變量 – 2013-02-28 11:27:39