类的加载原理下
上篇文章讲了类是如何加载的,但是我们只看到了类里面的方法,属性和协议的加载,并没有看到分类加载,这篇文章介绍分类的加载。
分类加载
1. 分类的本质
首先我们通过一个简单代码然后clang看一下cpp文件里代码
@interface NSObject (HFA)
@end
@implementation NSObject (HFA)
+ (void)load {
NSLog(@"HFA:%s", __FUNCTION__);
}
@end
int main(int argc, char * argv[]) {
NSString * appDelegateClassName;
@autoreleasepool {
// Setup code that might create autoreleased objects goes here.
appDelegateClassName = NSStringFromClass([AppDelegate class]);
}
return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}
通过clang后我们看到这么一个结构体:
struct _category_t {
const char *name;
struct _class_t *cls;
const struct _method_list_t *instance_methods;
const struct _method_list_t *class_methods;
const struct _protocol_list_t *protocols;
const struct _prop_list_t *properties;
};
static struct _category_t _OBJC_$_CATEGORY_NSObject_$_HFA __attribute__ ((used, section ("__DATA,__objc_const"))) =
{
"NSObject", // 这边是分类的名称,正常应该是HFA,但是却变成了NSObject,主要是因为目前是编译状态,我们的分类是在运行时被加载到类里面的,也是在那个时候才确定分类名称
0, // &OBJC_CLASS_$_NSObject,
0,
(const struct _method_list_t *)&_OBJC_$_CATEGORY_CLASS_METHODS_NSObject_$_HFA,
0,
0,
};
name
:分类名称
cls
:对应的类
instance_methods
:实例方法列表
class_methods
:类方法列表
protocols
:协议
properties
:属性
似乎类的信息该有的都有了,但是仔细一看少了成员变量,这就是为什么分类不能添加成员变量的原因。
总之分类呢本质也是一个结构体。
2. 分类加载的代码是哪里?
首先我们要先知道分类是在哪里被加载进来的?
我们添加了一个分类代码如下:
@implementation HFObject (HFA)
- (void)say666 {
NSLog(@"%s", __FUNCTION__);
}
- (void)say111 {
NSLog(@"%s", __FUNCTION__);
}
- (void)say222 {
NSLog(@"%s", __FUNCTION__);
}
+ (void)load {
NSLog(@"HFA:%s", __FUNCTION__);
}
@end
目前我们的分类有load
的方法,主类也有load
方法,然后继续上编文章的代码追踪
static void methodizeClass(Class cls, Class previously)
{
runtimeLock.assertLocked();
bool isMeta = cls->isMetaClass();
auto rw = cls->data();
auto ro = rw->ro();
auto rwe = rw->ext();
const char *mangledName = cls->nonlazyMangledName();
if (strcmp(mangledName, "HFObject") == 0 && !isMeta) {
auto ro = (class_ro_t *)cls->data();
printf("需要研究的类----%s\n", __FUNCTION__);
}
// Methodizing for the first time
if (PrintConnecting) {
_objc_inform("CLASS: methodizing class '%s' %s",
cls->nameForLogging(), isMeta ? "(meta)" : "");
}
// Install methods and properties that the class implements itself.
method_list_t *list = ro->baseMethods();
if (list) {
prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls), nullptr);
if (rwe)
rwe->methods.attachLists(&list, 1);
}
property_list_t *proplist = ro->baseProperties;
if (rwe && proplist) {
rwe->properties.attachLists(&proplist, 1);
}
protocol_list_t *protolist = ro->baseProtocols;
if (rwe && protolist) {
rwe->protocols.attachLists(&protolist, 1);
}
// Root classes get bonus method implementations if they don't have
// them already. These apply before category replacements.
if (cls->isRootMetaclass()) {
// root metaclass
addMethod(cls, @selector(initialize), (IMP)&objc_noop_imp, "", NO);
}
// Attach categories.
if (previously) {
if (isMeta) {
objc::unattachedCategories.attachToClass(cls, previously,
ATTACH_METACLASS);
} else {
// When a class relocates, categories with class methods
// may be registered on the class itself rather than on
// the metaclass. Tell attachToClass to look for those.
objc::unattachedCategories.attachToClass(cls, previously,
ATTACH_CLASS_AND_METACLASS);
}
}
objc::unattachedCategories.attachToClass(cls, cls,
isMeta ? ATTACH_METACLASS : ATTACH_CLASS);
}
通过上面代码我们知道主类在这边对方法进行了排序,初始化属性和协议,而在代码最后面objc::unattachedCategories.attachToClass(cls, cls, isMeta ? ATTACH_METACLASS : ATTACH_CLASS);
这边似乎就是对分类的加载。因此我们来到attachToClass
方法
void attachToClass(Class cls, Class previously, int flags)
{
runtimeLock.assertLocked();
ASSERT((flags & ATTACH_CLASS) ||
(flags & ATTACH_METACLASS) ||
(flags & ATTACH_CLASS_AND_METACLASS));
const char *mangledName = cls->nonlazyMangledName();
if (strcmp(mangledName, "HFObject") == 0) {
auto ro = (class_ro_t *)cls->data();
printf("需要研究的类----%s\n", __FUNCTION__);
}
auto &map = get();
auto it = map.find(previously);
if (it != map.end()) {
category_list &list = it->second;
if (flags & ATTACH_CLASS_AND_METACLASS) {
int otherFlags = flags & ~ATTACH_CLASS_AND_METACLASS;
attachCategories(cls, list.array(), list.count(), otherFlags | ATTACH_CLASS);
attachCategories(cls->ISA(), list.array(), list.count(), otherFlags | ATTACH_METACLASS);
} else {
attachCategories(cls, list.array(), list.count(), flags);
}
map.erase(it);
}
}
在这个方法里面我们似乎是找到了分类加载的方法attachCategories
,继续来看看attachCategories
代码
// Attach method lists and properties and protocols from categories to a class.
// Assumes the categories in cats are all loaded and sorted by load order,
// oldest categories first.
static void
attachCategories(Class cls, const locstamped_category_t *cats_list, uint32_t cats_count,
int flags)
{
if (slowpath(PrintReplacedMethods)) {
printReplacements(cls, cats_list, cats_count);
}
if (slowpath(PrintConnecting)) {
_objc_inform("CLASS: attaching %d categories to%s class '%s'%s",
cats_count, (flags & ATTACH_EXISTING) ? " existing" : "",
cls->nameForLogging(), (flags & ATTACH_METACLASS) ? " (meta)" : "");
}
/*
* Only a few classes have more than 64 categories during launch.
* This uses a little stack, and avoids malloc.
*
* Categories must be added in the proper order, which is back
* to front. To do that with the chunking, we iterate cats_list
* from front to back, build up the local buffers backwards,
* and call attachLists on the chunks. attachLists prepends the
* lists, so the final result is in the expected order.
*/
constexpr uint32_t ATTACH_BUFSIZ = 64;
method_list_t *mlists[ATTACH_BUFSIZ];
property_list_t *proplists[ATTACH_BUFSIZ];
protocol_list_t *protolists[ATTACH_BUFSIZ];
uint32_t mcount = 0;
uint32_t propcount = 0;
uint32_t protocount = 0;
bool fromBundle = NO;
bool isMeta = (flags & ATTACH_METACLASS);
auto rwe = cls->data()->extAllocIfNeeded();
const char *mangledName = cls->nonlazyMangledName();
if (strcmp(mangledName, "HFObject") == 0 && !isMeta) {
printf("需要研究的类----%s\n", __FUNCTION__);
}
for (uint32_t i = 0; i < cats_count; i++) {
auto& entry = cats_list[I];
method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
if (mlist) {
if (mcount == ATTACH_BUFSIZ) {
prepareMethodLists(cls, mlists, mcount, NO, fromBundle, __func__);
rwe->methods.attachLists(mlists, mcount);
mcount = 0;
}
mlists[ATTACH_BUFSIZ - ++mcount] = mlist;
fromBundle |= entry.hi->isBundle();
}
property_list_t *proplist =
entry.cat->propertiesForMeta(isMeta, entry.hi);
if (proplist) {
if (propcount == ATTACH_BUFSIZ) {
rwe->properties.attachLists(proplists, propcount);
propcount = 0;
}
proplists[ATTACH_BUFSIZ - ++propcount] = proplist;
}
protocol_list_t *protolist = entry.cat->protocolsForMeta(isMeta);
if (protolist) {
if (protocount == ATTACH_BUFSIZ) {
rwe->protocols.attachLists(protolists, protocount);
protocount = 0;
}
protolists[ATTACH_BUFSIZ - ++protocount] = protolist;
}
}
if (mcount > 0) {
prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount,
NO, fromBundle, __func__);
rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
if (flags & ATTACH_EXISTING) {
flushCaches(cls, __func__, [](Class c){
// constant caches have been dealt with in prepareMethodLists
// if the class still is constant here, it's fine to keep
return !c->cache.isConstantOptimizedCache();
});
}
}
rwe->properties.attachLists(proplists + ATTACH_BUFSIZ - propcount, propcount);
rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
}
image.png
当我们断点来到这边然后通过lldb调试查看entry.cat内容
image.png
在这边获取到了分类信息,并将分类挂载到数组
mlists
注意:
auto rwe = cls->data()->extAllocIfNeeded();
这边获取了rwe,还记得在上篇文章中我们说过将需要动态更新的部分提取出来存入class_rw_ext_t
即rwe
,而分类就是动态更新。
if (mcount > 0) {
prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount,
NO, fromBundle, __func__);
rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
if (flags & ATTACH_EXISTING) {
flushCaches(cls, __func__, [](Class c){
// constant caches have been dealt with in prepareMethodLists
// if the class still is constant here, it's fine to keep
return !c->cache.isConstantOptimizedCache();
});
}
}
这边即是将分类的方法进行了排序,然后添加到类里面。
这边又是如何添加到类里面呢?
void attachLists(List* const * addedLists, uint32_t addedCount) {
if (addedCount == 0) return;
if (hasArray()) {
// many lists -> many lists
uint32_t oldCount = array()->count;
uint32_t newCount = oldCount + addedCount;
array_t *newArray = (array_t *)malloc(array_t::byteSize(newCount));
newArray->count = newCount;
array()->count = newCount;
for (int i = oldCount - 1; i >= 0; I--)
newArray->lists[i + addedCount] = array()->lists[I];
for (unsigned i = 0; i < addedCount; I++)
newArray->lists[i] = addedLists[I];
free(array());
setArray(newArray);
validate();
}
else if (!list && addedCount == 1) {
// 0 lists -> 1 list
list = addedLists[0];
validate();
}
else {
// 1 list -> many lists
Ptr<List> oldList = list;
uint32_t oldCount = oldList ? 1 : 0;
uint32_t newCount = oldCount + addedCount;
setArray((array_t *)malloc(array_t::byteSize(newCount)));
array()->count = newCount;
if (oldList) array()->lists[addedCount] = oldList;
for (unsigned i = 0; i < addedCount; I++)
array()->lists[i] = addedLists[I];
validate();
}
}
首先我们来解读一下这块代码:
当array()
二维数组存在,即hasArray()为true
,则是新创建了一个了newArray
,然后原来的方法添加到后面,新的方法添加到前面。
当list
为空且指添加一个方法列表,直接list
指向该方法列表,当前是一维数组
当二维数组array
为空,且list
不为空,创建一个二维数组array
,将list
添加到末尾,新的数组添加到前面
总的来说如果没有分类就是一个一维数组,如果有分类,会创建一个二维数组,将主类的方法列表放在末尾,分类的方法列表放在前面,当objc_msgSend 发送消息调用方法时,找到了主类方法后会一直往前查找是否还有同名方法,其实就是查找分类方法,所以我们的分类方法会优先调用
上面已经证实了分类方法加载代码位置,接下来我们来分析什么时候调用
分类什么时候进行加载
目前我们已经确定分类加载是attachCategories
函数,接下来我们可以看看都有哪些调用
-
read_image
->realizeClassWithoutSwift
->methodizeClass
->attachToClass
->attachCategories
-
load_images
->loadAllCategories
->load_categories_nolock
->attachCategories
我们通过断点调试
image.png
发现走的是线路2,为什么走线路2呢?猜测应该是load_images要调用某个类的load方法,调用前先将该类初始化把方法都加载进来
目前先放一放,我们研究一下几种情况
- 主类和分类都有load方法
这种情况我们在上面已经分析过了,走的流程
read_image
->realizeClassWithoutSwift
->methodizeClass
->attachToClass
load_images
->loadAllCategories
->load_categories_nolock
->attachCategories
- 主类有load方法,分类没有
read_image
->realizeClassWithoutSwift
->methodizeClass
->attachToClass
- 主类没有load方法,分类有
read_image
->realizeClassWithoutSwift
->methodizeClass
->attachToClass
- 主类没有load方法,多个分类里面有load方法
read_image
->realizeClassWithoutSwift
->methodizeClass
->attachToClass
->attachCategories
现在就清晰的知道了线路1和线路2都是在什么情况走的了
现在还有一点就是2和3里面的分类是什么时候加载的呢?
首先我们先看看2:主类有load方法,分类没有
我们知道有load方法就是非懒加载类,就会来到realizeClassWithoutSwift
方法
去加载ro和rw,这时候我们来看看加载完后的ro
image.png
image.png
lldb调试就可以知道,ro里面已经加载了分类的方法了,也就是说从mach-o里面把类方法和分类方法都加载进来了
同样的3:主类没有load方法,分类有也是如此。
这边我们可以得出一个小小的结论:一个类的load方法越多会程序的启动时间越长,所以平时我们开发的时候除非必要,否则尽量少写load方法来影响程序启动。