在@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方法的数量。