isKindOfClass和isMemberOfClass的区别

turboksiOS78

+ (BOOL)isMemberOfClass:(Class)cls {

//    类的元类 与 传入类 对比

    return object_getClass((id)self) == cls;

}


- (BOOL)isMemberOfClass:(Class)cls {

//    对象的类 与 传入类 对比

    return [self class] == cls;

}


+ (BOOL)isKindOfClass:(Class)cls {

//    元类 --> 根元类 --> 根类 --> nil 与 传入类的对比

    for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) {

        if (tcls == cls) return YES;

    }

    return NO;

}


- (BOOL)isKindOfClass:(Class)cls {

//    对象的类 --> 父类 --> 根类 --> nil 与 传入类的对比

    for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {

        if (tcls == cls) return YES;

    }

    return NO;

}

测试代码:

        BOOL re1 = [(id)[NSObject class] isKindOfClass:[NSObject class]];

        BOOL re3 = [(id)[KSPerson class] isKindOfClass:[KSPerson class]];

        BOOL re2 = [(id)[NSObject class] isMemberOfClass:[NSObject class]];

        BOOL re4 = [(id)[KSPerson class] isMemberOfClass:[KSPerson class]];

        NSLog(@" \n re1 :%hhd\n re2 :%hhd\n re3 :%hhd\n re4 :%hhd\n",re1,re2,re3,re4);

        

        BOOL re5 = [(id)[NSObject alloc] isKindOfClass:[NSObject class]];

        BOOL re7 = [(id)[KSPerson alloc] isKindOfClass:[KSPerson class]];

        BOOL re6 = [(id)[NSObject alloc] isMemberOfClass:[NSObject class]];

        BOOL re8 = [(id)[KSPerson alloc] isMemberOfClass:[KSPerson class]];

        NSLog(@" \n re5 :%hhd\n re6 :%hhd\n re7 :%hhd\n re8 :%hhd\n",re5,re6,re7,re8);

结果:

2021-01-23 17:25:30.138090+0800 test[8101:257311]  

 re1 :1

 re2 :0

 re3 :0

 re4 :0

2021-01-23 17:25:30.138761+0800 test[8101:257311]  

 re5 :1

 re6 :1

 re7 :1

 re8 :1

Program ended with exit code: 0

相关文章

WKWebView

WKWebView

<!DOCTYPE html><head>    <title>HTML</title>    <meta...

CPU和GPU

CPU和GPU

    在屏幕成像的过程中,CPU和GPU起着至关重要的作用:CPU(Central Processing Unit,中央处理器)对象的创建和销毁、对象属性的调...

iOS基于SceneKit的3D汽车改色

iOS基于SceneKit的3D汽车改色

基于SceneKit的汽车改色,需要修改模型文件可以去 https://www.turbosquid.com/ 自行下载,免费资源还挺多的。先上个效果图吧:核心代码: &...

Runtime详解

Runtime详解

The Objective-C language defers as many decisions as it can from compile time and link time to runti...

RunLoop

RunLoop

RunLoop一、基础理论顾名思义1.    运行循环2.    在程序运行过程中循环做一些事情3.    是用户态和内核态之间的交互模式应...

GCD定时器

GCD定时器

NSTimer依赖于RunLoop,如果RunLoop的任务过于繁重,可能会导致NSTimer不准时。而GCD的定时器会更加准时。- (void)viewDidLoad {   ...