您可以使用类扩展。类扩展类似于类别,但没有任何名称。在 Apple 文档中,他们只定义了私有方法,但实际上您也可以声明内部变量。
我的类.h
@class PublicClass;
// Public interface
@interface MyClass : NSObject
@property (nonatomic, retain) PublicClass *publicVar;
@property (nonatomic, retain) PublicClass *publicVarDiffInternal;
- (void)publicMethod;
@end
我的班级.m
#import "PublicClass.h"
#import "InternalClass.h"
// Private interface
@interface MyClass ( /* class extension */ )
{
@private
// Internal variable only used internally
NSInteger defaultSize;
// Internal variable only used internally as private property
InternalClass *internalVar;
@private
// Internal variable exposed as public property
PublicClass *publicVar;
// Internal variable exposed as public property with an other name
PublicClass *myFooVar;
}
@property (nonatomic, retain) InternalClass *internalVar;
- (void)privateMethod;
@end
// Full implementation of MyClass
@implementation MyClass
@synthesize internalVar;
@synthesize publicVar;
@synthesize publicVarDiffInternal = myFooVar
- (void)privateMethod
{
}
- (void)publicMethod
{
}
- (id)init
{
if ((self = [super init]))
{
defaultSize = 512;
self.internalVar = nil;
self.publicVar = nil;
self.publicVarDiffInternal = nil; // initialize myFooVar
}
return self;
}
@end
您可以只使用您的公共 API 和公共属性将 MyClass.h 提供给任何人。在 MyClass.m 上,您在类扩展上声明您的成员变量 private 和 public,以及您的私有方法。
像这样很容易暴露公共接口并隐藏细节实现。我用在我的项目上没有任何麻烦。