首页 > 代码库 > OC中isKindOfClass与isMemberOfClass的区别

OC中isKindOfClass与isMemberOfClass的区别

先给出官方介绍

  • isKindOfClass:Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class.

  • isMemberOfClass:Returns a Boolean value that indicates whether the receiver is an instance of a given class.

共同点:

isKindOfClass与isMemberOfClass都是NSObject中比较Class的方法。

不同点:

1.isKindOfClass用来判断某个对象是否属于某个类,或者是属于某个派生类。

2.isMemberOfClass用来判断某个对象是否为当前类的实例。

PS:isMemberOfClass不能检测任何的类都是基于NSObject类这一事实,而isKindOfClass可以。

下面就用一个小栗子讲解一下两者的区别:

1、首先创建个People类基于NSObject,然后创建个Student类基于People类

- (void)viewDidLoad {
    [super viewDidLoad];
    
    People *people = [[People alloc] init];
    Student *student   = [[Student alloc] init];
    
    if ([people isKindOfClass:[People class]]) {
        NSLog(@"people iskinofclass People");
    }
    
    if ([people isKindOfClass:[NSObject class]]) {
        NSLog(@"people iskinofclass NSObject");
    }
  
    if ([student isMemberOfClass:[Student class]]) {
        NSLog(@"student ismemberOfClass People");
    }
    
    if (![student isMemberOfClass:[NSObject class]]) {
        NSLog(@"student isbelog NSObject");
    }
}

2、查看打印结果:四个log全部打印,验证了上边对两者的论述。

上述概念理解后作者给大家出个思考题如下:

    BOOL rez1 = [(id)[NSObject class] isKindOfClass:[NSObject class]];
    BOOL rez2 = [(id)[NSObject class] isMemberOfClass:[NSObject class]];
    BOOL rez3 = [(id)[Student class] isKindOfClass:[People class]];
    BOOL rez4 = [(id)[Student class] isMemberOfClass:[Student class]];

看看大家对这两者含义究竟了解了多少(如果一下子就答出来了,证明真的是懂了。)

———————————--------华丽的分割线——————————————————

最后给出输出结果:rez1为真、其他均为假。

 

 

 

OC中isKindOfClass与isMemberOfClass的区别