在块中定义您的私有方法@implementation
对于大多数用途来说是理想的。@implementation
无论声明顺序如何,Clang 都会在 中看到这些。无需在类延续(又名类扩展)或命名类别中声明它们。
在某些情况下,您需要在类延续中声明方法(例如,如果在类延续和 之间使用选择器@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;
// you can use a convention where the class name prefix is reserved
// for private methods this can reduce accidental overriding:
- (void)MONObject_privateMethod;
@end
// The potentially good thing about functions is that they are truly
// inaccessible; They may not be overridden, accidentally used,
// looked up via the objc runtime, and will often be eliminated from
// backtraces. Unlike methods, they can also be inlined. If unused
// (e.g. diagnostic omitted in release) or every use is inlined,
// they may be removed from the binary:
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;
}
// if declared in the @implementation scope, you *could* access the
// private ivars directly (although you should rarely do this):
pObject->anIvar = true;
}
- (void)publicMethod
{
// declared below -- but clang can see its declaration in this
// translation:
[self privateMethod];
}
// no declaration required.
- (void)privateMethod
{
}
- (void)MONObject_privateMethod
{
}
@end
另一种可能不明显的方法:C++ 类型既可以非常快,又可以提供更高程度的控制,同时最大限度地减少导出和加载的 objc 方法的数量。