iOS 类的结构分析(二)

2020-09-15  本文已影响0人  ugpass

1. 类对象获取

LSPerson *person = [[LSPerson alloc] init];
NSLog(@"[person class] = %@, isMetaClass=%d", [person class], class_isMetaClass([person class]));
NSLog(@"[LSPerson class] = %@, isMetaClass=%d", [LSPerson class], class_isMetaClass([LSPerson class]));

output:
//[person class] = LSPerson, isMetaClass=0
//[LSPerson class] = LSPerson, isMetaClass=0

根据以上代码可以看到不管是对象调用class方法还是类调用class方法,得到的都是类对象,且不是元类对象,那么class底层是如何实现的呢?

class源码

+ (Class)class {
    return self;
}

- (Class)class {
    return object_getClass(self);
}

可以看到class的类方法直接返回调用类的类对象;实例方法调用object_getClass且参数为实例对象。

object_getClass源码

Class object_getClass(id obj)
{
    if (obj) return obj->getIsa();
    else return Nil;
}

获取当前对象的isa并返回,之前已经分析过对象的isa指向当前的类对象。

总结:不管是对象调用class方法还是类调用class方法,返回的都是类对象。

2. 获取元类对象

那么如何获取元类对象呢?在runtime中有objc_getMetaClass(const char * _Nonnull name),参数是类名称的c语言字符串

const char *className = [NSStringFromClass([LSPerson class]) UTF8String];
Class metaClass = objc_getMetaClass(className);
        
NSLog(@"LSPerson metaClass = %@, isMetaClass=%d", metaClass, class_isMetaClass(metaClass));

output:
//LSPerson metaClass = LSPerson, isMetaClass=1

objc_getMetaClass源码

Class objc_getMetaClass(const char *aClassName)
{
    Class cls;

    if (!aClassName) return Nil;

    //根据类对象名称字符串获取类对象
    cls = objc_getClass (aClassName);
    if (!cls)
    {
        _objc_inform ("class `%s' not linked into application", aClassName);
        return Nil;
    }

    //返回类对象的isa指针指向 即元类对象
    return cls->ISA();
}

objc_getClass源码 根据字符串获取类

Class objc_getClass(const char *aClassName)
{
    if (!aClassName) return Nil;

    // NO unconnected, YES class handler
    return look_up_class(aClassName, NO, YES);
}

3. isKindOfClass和isMemberOfClass

isKindOfClass的对象方法 和 类方法

- (BOOL)isKindOfClass:(Class)cls {
    for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
        if (tcls == cls) return YES;
    }
    return NO;
}

+ (BOOL)isKindOfClass:(Class)cls {
    for (Class tcls = self->ISA(); tcls; tcls = tcls->superclass) {
        if (tcls == cls) return YES;
    }
    return NO;
}

分析:
- (BOOL)isKindOfClass:(Class)cls对象方法,首先获取对象的类对象tcls和要比较的对象cls进行比较,如果不想等则递归比较tcls的父类。
+ (BOOL)isKindOfClass:(Class)cls类方法,首先获取类的isa指针的指向,即元类tcls与要比较的cls进行比较,如果不想等,则递归查找tcls的父类进行比较

isMemberOfClass的对象方法 和 类方法

- (BOOL)isMemberOfClass:(Class)cls {
    return [self class] == cls;
}

+ (BOOL)isMemberOfClass:(Class)cls {
    return self->ISA() == cls;
}

分析:
- (BOOL)isMemberOfClass:(Class)cls对象方法,比较对象的类对象和cls是否想等。
+ (BOOL)isMemberOfClass:(Class)cls类方法,获取类对象的元类和cls比较是否想等。

题目解析:

//---类方法调用
BOOL re1 = [(id)[NSObject class] isKindOfClass:[NSObject class]];
//获取[NSObject class]的元类和[NSObject class]进行比较,不相等,则 
//查找[NSObject class]的元类的父类,根元类的父类指向根类,都为 
//[NSObject class]所以相等,结果为1

BOOL re2 = [(id)[NSObject class] isMemberOfClass:[NSObject class]];     
//获取[NSObject class]的元类和[NSObject class]比较,不相等,结果为0

BOOL re3 = [(id)[LSPerson class] isKindOfClass:[LSPerson class]];  
//获取[LSPerson class]的元类和[LSPerson class]进行比较,不相等
//则查找[LSPerson class]的元类的父类为根元类,和[LSPerson class]进行比较,不相等
//根元类的父类指向根类,和[LSPerson class]进行比较,不相等
//根类的父类指向nil,结果为0

BOOL re4 = [(id)[LSPerson class] isMemberOfClass:[LSPerson class]];       
//获取[LSPerson class]的元类和[LSPerson class]比较,不相等,结果为0

//---实例方法调用
BOOL re5 = [(id)[NSObject alloc] isKindOfClass:[NSObject class]];
//获取[NSObject alloc]的类对象[[NSObject alloc] class] 和 [NSObject class]比较相等,结果为1

BOOL re6 = [(id)[NSObject alloc] isMemberOfClass:[NSObject class]];     
//比较[NSObject alloc]的类对象[[NSObject alloc] class] 和 [NSObject class]相等,结果为1

BOOL re7 = [(id)[LSPerson alloc] isKindOfClass:[LSPerson class]];
//比较[LSPerson alloc]的类对象[[LSPerson alloc] class] 和 [LSPerson class]相等,结果为1

BOOL re8 = [(id)[LSPerson alloc] isMemberOfClass:[LSPerson class]];       
//比较[LSPerson alloc]的类对象[[LSPerson alloc] class] 和 [LSPerson class]相等,结果为1

注意:
不管是根据断点源码还是根据查看汇编,在调用isKindOfClass时并没有走到NSObject.mm中的isKindOfClass对象方法和类方法,反而走的是objc_opt_isKindOfClass,这是因为llvm对一些不经常重写的方法进行了优化,如果重写了,则进行msgSend消息发送流程。

llvm中对部分方法进行转发

// This is the table of ObjC "accelerated dispatch" functions.  They are a set
// of objc methods that are "seldom overridden" and so the compiler replaces the
// objc_msgSend with a call to one of the dispatch functions.  That will check
// whether the method has been overridden, and directly call the Foundation 
// implementation if not.  
// This table is supposed to be complete.  If ones get added in the future, we
// will have to add them to the table.
const char *AppleObjCTrampolineHandler::g_opt_dispatch_names[] = {
    "objc_alloc",
    "objc_autorelease",
    "objc_release",
    "objc_retain",
    "objc_alloc_init",
    "objc_allocWithZone",
    "objc_opt_class",
    "objc_opt_isKindOfClass",
    "objc_opt_new",
    "objc_opt_respondsToSelector",
    "objc_opt_self",
};

objc_opt_isKindOfClass源码

// Calls [obj isKindOfClass]
BOOL
objc_opt_isKindOfClass(id obj, Class otherClass)
{
#if __OBJC2__
    printf("objc_opt_isKindOfClass(id obj, Class otherClass)");
    if (slowpath(!obj)) return NO;
    Class cls = obj->getIsa();
    if (fastpath(!cls->hasCustomCore())) {
        for (Class tcls = cls; tcls; tcls = tcls->superclass) {
            if (tcls == otherClass) return YES;
        }
        return NO;
    }
#endif
    return ((BOOL(*)(id, SEL, Class))objc_msgSend)(obj, @selector(isKindOfClass:), otherClass);
}

分析:如果是objc2,则根据传入对象的isa获取到Class cls,此处如果传入实例对象则获取类对象,如果传入类对象,则获取元类,然后递归cls及其父类,和otherClass进行比较。

4. class_getClassMethod底层实现

Method class_getClassMethod(Class cls, SEL sel)
{
    if (!cls  ||  !sel) return nil;

    return class_getInstanceMethod(cls->getMeta(), sel);
}

Class getMeta() {
        if (isMetaClass()) return (Class)this;
        else return this->ISA();
    }

可以看到,获取类方法其实是根据类找到元类,然后去元类中找实例方法,从而侧面证明了,在OC中区分的对象方法和类方法,其实在C和C++层面并没有区分,都是方法,只是存储的位置不一样。

class_getInstanceMethod源码

Method class_getInstanceMethod(Class cls, SEL sel)
{
    if (!cls  ||  !sel) return nil;

    // This deliberately avoids +initialize because it historically did so.

    // This implementation is a bit weird because it's the only place that 
    // wants a Method instead of an IMP.

#warning fixme build and search caches
        
    // Search method lists, try method resolver, etc.
    lookUpImpOrForward(nil, sel, cls, LOOKUP_RESOLVER);

#warning fixme build and search caches

    return _class_getMethod(cls, sel);
}

static Method _class_getMethod(Class cls, SEL sel)
{
    mutex_locker_t lock(runtimeLock);
    return getMethod_nolock(cls, sel);
}

static method_t *
getMethod_nolock(Class cls, SEL sel)
{
    method_t *m = nil;

    runtimeLock.assertLocked();

    // fixme nil cls?
    // fixme nil sel?

    ASSERT(cls->isRealized());
    
    while (cls  &&  ((m = getMethodNoSuper_nolock(cls, sel))) == nil) {
        cls = cls->superclass;
    }

    return m;
}

注意:while循环是从cls开始,递归其父类进行查找,所以如果在元类中查找类方法,直到根元类仍没有找到,则因为根元类的父类为根类即NSObject,如果在NSObject中实现了同名的对象方法,仍然不会报错。

image.png

如上图所示,如果调用[LSStudent sleep];,并不会报unrecognized selector sent to class的错误,反而会调用根类中的- (void)sleep实例方法。

上一篇下一篇

猜你喜欢

热点阅读