isKindOfClass与isMemberOfClass的区别

源码分析:

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

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

+ (BOOL)isKindOfClass:(Class)cls {
    // 获取的是该类的meta class
    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;
}
class和meta class关系

总结:

  • + (BOOL)isMemberOfClass: 是判断该类的meta class是否和class相等。
  • - (BOOL)isMemberOfClass:判断该对象所属的类是和class相等,即用于判断一个对象是否属于当前这个类。
  • + (BOOL)isKindOfClass:循环遍历该类的meta classsuper class,判断是否和class相等(只有NSObjectmeta classsuper class等于NSObject)。
  • - (BOOL)isKindOfClass:循环遍历该对象所属的类及super class,判断是否和class相等,即用于判断当前对象是否属于这个类或者这个类的子类;。

iOS面试题汇总

你可能感兴趣的:(isKindOfClass与isMemberOfClass的区别)