//优化缓存查找传入的参数cache 用于表示是否找到cache的布尔量, //从_class_lookupMethodAndLoadCache3进来的是在缓存中已经找过并且没找到的情景,这时候cache为NO if (cache) { //如果传入的是YES,那么就会调用cache_getImp方法去找到缓存里面的IMP,注意cache_getImp是通过汇编实现的,cache_getImp会把找到的IMP放在r11中 imp = cache_getImp(cls, sel); if (imp) return imp; }
//锁住读写锁 runtimeLock.lock(); //....... //如果已经初始化会在objc_class对应的标识位设置为true if (!cls->isRealized()) { //实例化类结构 realizeClass(cls); }
// +initialize就是在这个阶段调用的 if (initialize && !cls->isInitialized()) { runtimeLock.unlock(); //_class_initialize是类初始化的过程。它会发送一个initialize消息给当前类 _class_initialize (_class_getNonMetaClass(cls, inst)); runtimeLock.lock(); //如果我们发送的sel就是initialize那么这里的_class_initialize会发送一次+initialize,后续还会发送一次+initialize,但是这种情况很少见 // If sel == initialize, _class_initialize will send +initialize and // then the messenger will send +initialize again after this // procedure finishes. Of course, if this is not being called // from the messenger then it won't happen. 2778172 }
retry: runtimeLock.assertLocked();
// 从缓存中查找方法实现 imp = cache_getImp(cls, sel); if (imp) goto done;
//尝试在本类的方法列表中查找 { Method meth = getMethodNoSuper_nolock(cls, sel); if (meth) { //找到的情况下添加到缓存并返回方法实现 log_and_fill_cache(cls, meth->imp, sel, inst, cls); imp = meth->imp; goto done; } } //尝试在父类的缓存和方法列表中查找 { //如果以上尝试都失败了,接下来就会循环尝试父类的缓存和方法列表。一直找到NSObject为止。因为NSObject的superclass为nil,才跳出循环。 unsigned attempts = unreasonableClassCount(); for (Class curClass = cls->superclass; curClass != nil; curClass = curClass->superclass) { // Halt if there is a cycle in the superclass chain. if (--attempts == 0) { _objc_fatal("Memory corruption in class list."); } // Superclass cache. imp = cache_getImp(curClass, sel); if (imp) { if (imp != (IMP)_objc_msgForward_impcache) { // Found the method in a superclass. Cache it in this class. log_and_fill_cache(cls, imp, sel, inst, curClass); goto done; } else { // Found a forward:: entry in a superclass. // Stop searching, but don't cache yet; call method // resolver for this class first. break; } } // Superclass method list. Method meth = getMethodNoSuper_nolock(curClass, sel); if (meth) { log_and_fill_cache(cls, meth->imp, sel, inst, curClass); imp = meth->imp; goto done; } } } //没有找到实现方法,尝试寻找方法的解决者 // No implementation found. Try method resolver once. if (resolver && !triedResolver) { runtimeLock.unlock(); //如果父类找到NSObject还没有找到,那么就会开始尝试_class_resolveMethod方法。 //注意,这些需要打开读锁,因为开发者可能会在这里动态增加方法实现,所以不需要缓存结果。 //此处虽然锁被打开,可能会出现线程问题,所以在执行完_class_resolveMethod方法之后,会goto retry,重新执行一遍之前查找的过程。 // try [nonMetaClass resolveClassMethod:sel] // and [cls resolveInstanceMethod:sel] _class_resolveMethod(cls, sel, inst); runtimeLock.lock(); //寻找用户指定的方法的解决者 // Don't cache the result; we don't hold the lock so it may have // changed already. Re-do the search from scratch instead. triedResolver = YES; //重新查找 goto retry; }