我们在iOS底层原理之_objc_msgSend方法查找中知道,_objc_msgSend主要是通过汇编快速找到方法的,这次我们研究方法慢速查找。
准备工作
代码准备
我们还是定义一个继承与NSObject的类,命名为LGPerson,在该类中定义一个实例方法,不用去实现(为了方便探究慢速查找的流程)
@interface LGPerson : NSObject
- (void)sayHello;
@end
在main函数中
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
LGPerson *person = [LGPerson alloc];
[person sayHello];
}
return 0;
}
引入lookUpImpOrForward
在 [person sayHello]处打上断点,运行代码,查看汇编我们找到
objc_msgSend方法点击进入从
objc_msgSend方法中找到进入到objc_msgSend_uncached方法并进入在
objc_msgSend_uncached方法中找到了lookUpImpOrForward方法及其在源码文件的位置
lookUpImpOrForward方法探究
lookupImpOrForward源码
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
IMP imp = nil;
Class curClass;
runtimeLock.assertUnlocked();
// Optimistic cache lookup
if (fastpath(behavior & LOOKUP_CACHE)) {
imp = cache_getImp(cls, sel);
if (imp) goto done_nolock;
}
runtimeLock.lock();
checkIsKnownClass(cls);
if (slowpath(!cls->isRealized())) {
cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
// runtimeLock may have been dropped but is now locked again
}
if (slowpath((behavior & LOOKUP_INITIALIZE) && !cls->isInitialized())) {
cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
}
runtimeLock.assertLocked();
curClass = cls;
for (unsigned attempts = unreasonableClassCount();;) {
// curClass method list.
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
imp = meth->imp;
goto done;
}
if (slowpath((curClass = curClass->superclass) == nil)) {
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = forward_imp;
break;
}
// Halt if there is a cycle in the superclass chain.
if (slowpath(--attempts == 0)) {
_objc_fatal("Memory corruption in class list.");
}
// Superclass cache.
imp = cache_getImp(curClass, sel); // 有问题???? cache_getImp - lookup - lookUpImpOrForward
if (slowpath(imp == forward_imp)) {
break;
}
if (fastpath(imp)) {
goto done;
}
}
if (slowpath(behavior & LOOKUP_RESOLVER)) {
behavior ^= LOOKUP_RESOLVER;
return resolveMethod_locked(inst, sel, cls, behavior);
}
done:
log_and_fill_cache(cls, imp, sel, inst, curClass);
runtimeLock.unlock();
done_nolock:
if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
return nil;
}
return imp;
}
lookupImpOrForward源码分析
lookupImpOrForward主要就是查找方法并返回imp
_objc_msgForward_impcache:从缓存中查找方法checkIsKnownClass:当前要查找的类是否是系统已知的,即是否是我们创建的,只有是系统已知的才能对方法、属性、协议等存储以及查找realizeClassMaybeSwiftAndLeaveLocked:该方法主要是获得当前对象继承关系,部分代码如下initializeAndLeaveLocked:主要是系统方法的自动调用,比如initalize或者reload等getMethodNoSuper_nolock:从当前类查找方法slowpath((curClass = curClass->superclass) == nil:从父类查找方法,并将父类赋值给curClassimp = cache_getImp(curClass, sel):从当前类(已经是父类了)的缓存中查找resolveMethod_locked:当前类、父类均没有找到则给予一次补救机会
done方法分析
log_and_fill_cache
代码
log_and_fill_cache(Class cls, IMP imp, SEL sel, id receiver, Class implementer)
{
#if SUPPORT_MESSAGE_LOGGING
if (slowpath(objcMsgLogEnabled && implementer)) {
bool cacheIt = logMessageSend(implementer->isMetaClass(),
cls->nameForLogging(),
implementer->nameForLogging(),
sel);
if (!cacheIt) return;
}
#endif
// objc_msgSend -> 二分查找自己 -> cache_fill -> objc_msgSend
//
cache_fill(cls, sel, imp, receiver);
}
我们点击cache_fill方法进入查看
getMethodNoSuper_nolock方法查找探究
源码
getMethodNoSuper_nolock(Class cls, SEL sel)
{
runtimeLock.assertLocked();
ASSERT(cls->isRealized());
// fixme nil cls?
// fixme nil sel?
auto const methods = cls->data()->methods();
for (auto mlists = methods.beginLists(),
end = methods.endLists();
mlists != end;
++mlists)
{
method_t *m = search_method_list_inline(*mlists, sel);
if (m) return m;
}
return nil;
}
点击search_method_list_inline方法,在search_method_list_inline中查找findMethodInSortedMethodList
findMethodInSortedMethodList分析
源码实现
ALWAYS_INLINE static method_t *
findMethodInSortedMethodList(SEL key, const method_list_t *list)
{
ASSERT(list);
const method_t * const first = &list->first;
const method_t *base = first;
const method_t *probe;
uintptr_t keyValue = (uintptr_t)key;
uint32_t count;
for (count = list->count; count != 0; count >>= 1) {
probe = base + (count >> 1);
uintptr_t probeValue = (uintptr_t)probe->name;
if (keyValue == probeValue) {
// `probe` is a match.
// Rewind looking for the *first* occurrence of this value.
// This is required for correct category overrides.
while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
probe--;
}
return (method_t *)probe;
}
if (keyValue > probeValue) {
base = probe + 1;
count--;
}
}
return nil;
}
从源码我们可以分析得出,方法列表一定是有序的,因为使用了二分查找,为什么是二分查找呢?重点是count >> 1,比如0000 1000为8,左移一位变为0000 0100成为4,所以是二分查找。该方法最终实现了在方法列表中查找方法的实现。(二分法速度还是可以的,对于查找有兴趣的可以查看数据结构与算法之查找专题)
方法慢速查找总结
- 从缓存中查找,找到则返回,否则进入方法列表
- 从方法列表查找,此处使用二分查找,找到则返回,没有找到,若父类存在则进入父类查找,否则在返回nil之前有一次处理机会
- 将父类赋值给当前类,重复上述动作,直到父类不存在
- 最终找到imp则存入缓存中