isKindOfClass、isMemberOfClass

+(BOOL) isKindOfClass: (Class)aClass: aClass为self的元类对象,或者元类对象的父对象,才返回YES
-(BOOL) isKindOfClass: (Class)aClass:如果self为实例对象,aClass传入的是类对象或者类对象的父对象时,或者self为类对象,aClass为元类对象或者元类对象的父对象时,才返回YES
+(BOOL) isMemberOfClass: (Class)aClass:aClass为self的元类对象,才返回YES
-(BOOL) isMemberOfClass: (Class)aClass:如果self为实例对象,aClass传入的是类对象,或者self为类对象,aClass为元类对象,才返回YES

  • isKindOfClassisMemberOfClass的共通点是selfaClass的关系,即:
    aClass、object_getClass(self)进行比较
  • 苹果官方对外暴漏的API中没有+(BOOL) isKindOfClass: (Class)aClass+(BOOL) isMemberOfClass: (Class)aClass两个类方法,但其实是有的,以下方法可以猜想并验证
    如何查看方法类型01.png

    如何查看方法类型02.png

或者通过控制台打印IMP查看


如何查看方法类型03.png

以下是模拟内部实现的代码

int GSObjCIsKindOf(Class cls, Class other)
 {
 while (cls != Nil)
 {
 if (cls == other)
 {
 return YES;
 }
 cls = class_getSuperclass(cls);
 }
 return NO;
 }

+ (BOOL) isKindOfClass: (Class)aClass
{
    Class class = object_getClass(self);
    return GSObjCIsKindOf(class, aClass);
}

- (BOOL) isKindOfClass: (Class)aClass
{
    Class class = object_getClass(self);

    return GSObjCIsKindOf(class, aClass);
}

+ (BOOL) isMemberOfClass: (Class)aClass
{
    Class class = object_getClass(self);
    return (class == aClass) ? YES : NO;
}

- (BOOL) isMemberOfClass: (Class)aClass
{
    Class class = object_getClass(self);
    return (class == aClass) ? YES : NO;
}

你可能感兴趣的:(isKindOfClass、isMemberOfClass)