load
class
在 obj-c 运行时添加 a 时调用。
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/#//apple_ref/occ/clm/NSObject/load
因此,假设 aUIViewController
被添加到已经包含viewWillAppear:
但您希望它被另一个实现替换的 obj-c 运行时中。所以首先你添加一个新方法xxxWillAppear:
。现在一旦xxxWillAppear:
在ViewController
课堂上添加了,你就可以替换它。
但作者也说:
例如,假设我们想要跟踪每个视图控制器在 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/