美文网首页Runtime & Runloop
Runtime:isMemberOfClass与isKindOf

Runtime:isMemberOfClass与isKindOf

作者: 码小菜 | 来源:发表于2020-02-23 18:47 被阅读0次
夜景

目录
一,实例方法
二,类方法

一,实例方法

1,实例代码

Person *person = [Person new];
NSLog(@"%d", [person isMemberOfClass:[Person class]]);
NSLog(@"%d", [person isMemberOfClass:[NSObject class]]);
NSLog(@"%d", [person isKindOfClass:[Person class]]);
NSLog(@"%d", [person isKindOfClass:[NSObject class]]);

// 打印
1
0
1
1

2,底层代码(源码下载地址

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

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

3,说明

  • isMemberOfClass:该实例对象是否属于某个类

  • isKindOfClass:该实例对象是否属于某个类或其子类

二,类方法

1,实例代码

NSLog(@"%d", [Person isMemberOfClass:[Person class]]);
NSLog(@"%d", [Person isMemberOfClass:[NSObject class]]);
NSLog(@"%d", [Person isKindOfClass:[Person class]]);
NSLog(@"%d", [Person isKindOfClass:[NSObject class]]);

// 打印
0
0
0
1

2,底层代码

// self是class对象,object_getClass(self)是meta-class对象

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

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

3,说明

  • isMemberOfClass:该类是否等于某个类

  • isKindOfClass:该类是否等于某个类或其子类

4,分析

  • 方法内部是用meta-class对象进行判断的,而传进去的是class对象,所以前三个都是0,必须传meta-class对象才能得到正确的结果
NSLog(@"%d", [Person isMemberOfClass:object_getClass([Person class])]);
NSLog(@"%d", [Person isMemberOfClass:object_getClass([NSObject class])]);
NSLog(@"%d", [Person isKindOfClass:object_getClass([Person class])]);

// 打印
1
0
1
  • 第四个虽然传的是class对象,但Person的meta-class对象通过superclass指针可以找到NSObject的class对象,所以结果是1
superclass指针

相关文章

网友评论

    本文标题:Runtime:isMemberOfClass与isKindOf

    本文链接:https://www.haomeiwen.com/subject/fdgdqhtx.html