iOS底层原理之方法慢速查找探究

微信扫一扫,分享到朋友圈

iOS底层原理之方法慢速查找探究

我们在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:从父类查找方法,并将父类赋值给curClass
imp = 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则存入缓存中

谷歌:Chrome应用商店永久禁用付费扩展

上一篇

马斯克用一块新电池,引发电动车价格革命

下一篇

你也可能喜欢

iOS底层原理之方法慢速查找探究

长按储存图像,分享给朋友