在@implementation
块中定义您的私有方法是大多数情况下的理想选择。无论声明顺序如何,Clang都会在@implementation
中看到这些方法。没有必要在类扩展(也称为类别)或命名类别中声明它们。
在某些情况下,您需要在类扩展中声明该方法(例如,如果在类扩展和@implementation
之间使用选择器)。
static
函数非常适合特别敏感或速度关键的私有方法。
使用命名前缀的约定可以帮助您避免意外覆盖私有方法(我发现将类名作为前缀是安全的)。
命名类别(例如@interface MONObject(PrivateStuff)
)不是一个特别好的选择,因为在加载时可能会出现名称冲突。它们真正有用的只有友元或受保护的方法(这很少是一个好选择)。为确保您收到未完成类别实现的警告,您应该实际实现它:
@implementation MONObject (PrivateStuff)
...HERE...
@end
这是一个小的带注释的备忘单:
MONObject.h
@interface MONObject : NSObject
// public declaration required for clients' visibility/use.
@property (nonatomic, assign, readwrite) bool publicBool;
// public declaration required for clients' visibility/use.
- (void)publicMethod;
@end
MONObject.m
@interface MONObject ()
@property (nonatomic, assign, readwrite) bool privateBool;
- (void)MONObject_privateMethod;
@end
static void PrivateMethod(MONObject * pObject) {
pObject.privateBool = true;
}
@implementation MONObject
{
bool anIvar;
}
static void AnotherPrivateMethod(MONObject * pObject) {
if (0 == pObject) {
assert(0 && "invalid parameter");
return;
}
pObject->anIvar = true;
}
- (void)publicMethod
{
[self privateMethod];
}
- (void)privateMethod
{
}
- (void)MONObject_privateMethod
{
}
@end
另一种可能不太明显的方法是:C++类型既可以非常快速,又可以提供更高程度的控制,同时最小化导出和加载的Objective-C方法数量。