load 在 obj-c 运行时添加 class 时被调用。
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/#//apple_ref/occ/clm/NSObject/load
假设 UIViewController 被添加到已经包含 viewWillAppear: 的 obj-c 运行时中,但您希望它被另一个实现替换。所以首先你添加一个新方法xxxWillAppear:。
现在一旦在ViewController 类中添加了xxxWillAppear:,只有这样你才能替换它。
但是作者也说了:
例如,假设我们想要跟踪每个视图控制器在 iOS 应用中呈现给用户的次数
所以他试图演示一个应用程序可能有许多视图控制器但您不想继续为每个ViewController 替换viewWillAppear: 实现的情况。一旦viewWillAppear:的点被替换,那么不需要添加,只需要进行交换。
也许 Objective C 运行时的源代码可能会有所帮助:
/**********************************************************************
* addMethod
* fixme
* Locking: runtimeLock must be held by the caller
**********************************************************************/
static IMP
addMethod(Class cls, SEL name, IMP imp, const char *types, BOOL replace)
{
IMP result = nil;
rwlock_assert_writing(&runtimeLock);
assert(types);
assert(cls->isRealized());
method_t *m;
if ((m = getMethodNoSuper_nolock(cls, name))) {
// already exists
if (!replace) {
result = _method_getImplementation(m);
} else {
result = _method_setImplementation(cls, m, imp);
}
} else {
// fixme optimize
method_list_t *newlist;
newlist = (method_list_t *)_calloc_internal(sizeof(*newlist), 1);
newlist->entsize_NEVER_USE = (uint32_t)sizeof(method_t) | fixed_up_method_list;
newlist->count = 1;
newlist->first.name = name;
newlist->first.types = strdup(types);
if (!ignoreSelector(name)) {
newlist->first.imp = imp;
} else {
newlist->first.imp = (IMP)&_objc_ignored_method;
}
attachMethodLists(cls, &newlist, 1, NO, NO, YES);
result = nil;
}
return result;
}
BOOL
class_addMethod(Class cls, SEL name, IMP imp, const char *types)
{
if (!cls) return NO;
rwlock_write(&runtimeLock);
IMP old = addMethod(cls, name, imp, types ?: "", NO);
rwlock_unlock_write(&runtimeLock);
return old ? NO : YES;
}
IMP
class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
{
if (!cls) return nil;
rwlock_write(&runtimeLock);
IMP old = addMethod(cls, name, imp, types ?: "", YES);
rwlock_unlock_write(&runtimeLock);
return old;
}
如果你愿意,你可以挖掘更多:
http://www.opensource.apple.com/source/objc4/objc4-437/