关于runtime的objc_getClass和object_getclass

objc_getClass参数是类名的字符串,返回的就是这个类的类对象;object_getClass参数是id类型,它返回的是这个id的isa指针所指向的Class,如果传参是Class,则返回该Class的metaClass。

    Class currentClass = [self class];
    const char *a = object_getClassName(currentClass);
    for (int i = 1; i < 5; i++) {
        NSLog(@"Following the isa pointer %d times gives %p---%s", i, currentClass,a);
        currentClass = object_getClass(currentClass);
        a = object_getClassName(currentClass);
    }

上面一段代码输出的是:
Following the isa pointer 1 times gives 0x7fe273f0a880—DBTestView
Following the isa pointer 2 times gives 0x7fe273f0a8b0—NSObject
Following the isa pointer 3 times gives 0x100eaa198—NSObject
Following the isa pointer 4 times gives 0x100eaa198—NSObject,
由此我们可以看到,object_getClass返回的其实是class的metaClass,即Class这个类对象的类,这个概念有点绕。梳理一下:DBTestView这么一个类(0x7fe273f0a880),它的isa指针指向其元类(地址0x7fe273f0a8b0),这个元类的isa指针指向基类NSObject的元类,即根元类(0x100eaa198),再递进一层可以发现,根元类的isa指针指向自己,这样就形成了一个完整的闭环。

换一套实现:

    Class currentClass = [self class];
    const char *a = object_getClassName(currentClass);
    for (int i = 1; i < 5; i++) {
        NSLog(@"Following the isa pointer %d times gives %p---%s", i, currentClass,a);
        currentClass = objc_getClass([NSStringFromClass(currentClass)UTF8String]);
        a = object_getClassName(currentClass);
    }

输出为:
Following the isa pointer 1 times gives 0x7ff931e239a0—DBTestView
Following the isa pointer 2 times gives 0x7ff931e239a0—DBTestView
Following the isa pointer 3 times gives 0x7ff931e239a0—DBTestView
Following the isa pointer 4 times gives 0x7ff931e239a0—DBTestView
由此可知objc_getClass方法只是单纯地返回了Class,而非isa指针指向的Class。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值