isKindOfClass 和 isMemberOfClass 源码

+ (Class)class {
    return self;
}

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

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

inline Class 
objc_object::getIsa() 
{
    if (isTaggedPointer()) {
        uintptr_t slot = ((uintptr_t)this >> TAG_SLOT_SHIFT) & TAG_SLOT_MASK;
        return objc_tag_classes[slot];
    }
    return ISA();
}

inline Class 
objc_object::ISA() 
{
    assert(!isTaggedPointer()); 
    return (Class)(isa.bits & ISA_MASK);
}

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

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

+ (BOOL)isMemberOfClass:(Class)cls {
    return object_getClass((id)self) == cls;
}

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

总结

  + isKindOfClass 会拿到当前类对象的 isA(metaclass ) 递归(superclass)和当前比较是否相等 
  +  isMemberOfClass的源码实现是拿到自己的isa指针和自己比较,是否相等
  - isKindOfClass 会拿到当前实例对象的 class 递归(superclass)的和当前类对象进行比较 
  -  isMemberOfClass 会拿到当前实例对象的类对象 和当前 实例对象比较

你可能感兴趣的:(isKindOfClass 和 isMemberOfClass 源码)