首先class的结构体
struct objc_class : objc_object {
objc_class(const objc_class&) = delete;
objc_class(objc_class&&) = delete;
void operator=(const objc_class&) = delete;
void operator=(objc_class&&) = delete;
// Class ISA;
Class superclass;
cache_t cache; // formerly cache pointer and vtable
class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags
//省略方法信息................
}
cache_t cache是和objc_msgSend在执行方法调用时密切相关的一个联合体。它有临时缓存方法的作用,在我们调用方法时,如果cache中存在的时候,直接从cache中获取相关发放信息。 当objc_msgSend(receiver,sel...),走快速查找流程,在cache中查找方法时,流程如下
- 判断receiver是否存在
- 找到获取receiver中的isa指针,找到对应指向的类或者元类calss
- 通过class内存平移,获取到cache联合体
- 获取cache中的buchets,buchets中有对相关缓存方法的存储
- buchets中有对应的sel,调用imp,链接调用方法如果没有结束快速查找流程 当此快速查找完成,没有查找到后
会调用objc_msgSend_uncached方法,重新执行查找 此处也是混编语言,到最后会执行到
执行_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();
if (slowpath(!cls->isInitialized())) {
// The first message sent to a class is often +new or +alloc, or +self
// which goes through objc_opt_* or various optimized entry points.
//
// However, the class isn't realized/initialized yet at this point,
// and the optimized entry points fall down through objc_msgSend,
// which ends up here.
//
// We really want to avoid caching these, as it can cause IMP caches
// to be made with a single entry forever.
//
// Note that this check is racy as several threads might try to
// message a given class for the first time at the same time,
// in which case we might cache anyway.
behavior |= LOOKUP_NOCACHE;
}
// runtimeLock is held during isRealized and isInitialized checking
// to prevent races against concurrent realization.
// runtimeLock is held during method search to make
// method-lookup + cache-fill atomic with respect to method addition.
// Otherwise, a category could be added but ignored indefinitely because
// the cache was re-filled with the old value after the cache flush on
// behalf of the category.
runtimeLock.lock();
// We don't want people to be able to craft a binary blob that looks like
// a class but really isn't one and do a CFI attack.
//
// To make these harder we want to make sure this is a class that was
// either built into the binary or legitimately registered through
// objc_duplicateClass, objc_initializeClassPair or objc_allocateClassPair.
checkIsKnownClass(cls);
cls = realizeAndInitializeIfNeeded_locked(inst, cls, behavior & LOOKUP_INITIALIZE);
// runtimeLock may have been dropped but is now locked again
runtimeLock.assertLocked();
curClass = cls;
// The code used to lookup the class's cache again right after
// we take the lock but for the vast majority of the cases
// evidence shows this is a miss most of the time, hence a time loss.
//
// The only codepath calling into this without having performed some
// kind of cache lookup is class_getInstanceMethod().
for (unsigned attempts = unreasonableClassCount();;) {
if (curClass->cache.isConstantOptimizedCache(/* strict */true)) {
//再一次从cache里面去找imp
//目的:防止多线程操作时,刚好调用函数,此时缓存进来了
#if CONFIG_USE_PREOPT_CACHES
imp = cache_getImp(curClass, sel);
if (imp) goto done_unlock;
curClass = curClass->cache.preoptFallbackClass();
#endif
} else {
// curClass method list.
method_t *meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
imp = meth->imp(false);
goto done;
}
if (slowpath((curClass = curClass->getSuperclass()) == 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);
if (slowpath(imp == forward_imp)) {
// Found a forward:: entry in a superclass.
// Stop searching, but don't cache yet; call method
// resolver for this class first.
break;
}
if (fastpath(imp)) {
// Found the method in a superclass. Cache it in this class.
goto done;
}
}
// No implementation found. Try method resolver once.
if (slowpath(behavior & LOOKUP_RESOLVER)) {
behavior ^= LOOKUP_RESOLVER;
return resolveMethod_locked(inst, sel, cls, behavior);
}
done:
if (fastpath((behavior & LOOKUP_NOCACHE) == 0)) {
#if CONFIG_USE_PREOPT_CACHES
while (cls->cache.isConstantOptimizedCache(/* strict */true)) {
cls = cls->cache.preoptFallbackClass();
}
#endif
log_and_fill_cache(cls, imp, sel, inst, curClass);
}
done_unlock:
runtimeLock.unlock();
if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
return nil;
}
return imp;
}
粗略解释下以上方法执行的干了些啥事情
- 查找自己当前的方法列表,methodList,如果没有执行2
- 查找父类的cache,如果没有找到执行3
- 查找父类的方法列表,此过程如果父类没有一直会查找到顶级父类NSObject,如果没有转发消息
补充下cache的方法缓存策略
在arm64结构,也就是真机环境下,刚开始初始化的缓存⽅法的容器的⻓度2,当容器的⻓度 ⼩于8时,是满容量了才扩容。当容器的⻓度⼤于8时,是7/8扩容。也就是说当容器的⻓度为 8时,容器可以存储8个⽅法。当容器的⻓度为16时,当第15个⽅法需要存储进来的时候,容 器就要扩容了。
在x86_64架构下,刚开始初始化的容器的⻓度为4,是3/4扩容。这⾥的3/4扩容指的是:如果 容器的⻓度为4,当第3个数据需要存储的时候,就要扩容了。如果容器的⻓度为8,当第6个 数据需要存储的时候,就要扩容了。也就是说容器只能存储容器⻓度的3/4减1个⽅法。 还有⼀点就是:当容器扩容之后,前⾯存储的⽅法也会随之清空。