首页 > 代码库 > isKindOfClass和isMemberOfClass 的区别

isKindOfClass和isMemberOfClass 的区别

判断对象类型

-(BOOL) isKindOfClass: classObj判断是否是这个类或者这个类的子类的实例

-(BOOL) isMemberOfClass: classObj 判断是否是这个类的实例

测试实例:

新建Person类继承NSObject,新建Teacher类继承Person

 新建Person类:

#import <Foundation/Foundation.h>  
  
@interface Person : NSObject  
{  
    NSString *name;  
}  
-(void)setName:(NSString*)n;  
  
@end
#import "Person.h"  
  
@implementation Person  
-(void)setName:(NSString *)n  
{  
    name = n;  
}  
  
@end  

新建Teacher类

#import "Person.h"  
  
@interface Teacher : Person  
  
-(void)teach;  
  
@end 
#import "Teacher.h"  
  
@implementation Teacher  
-(void)teach  
{  
    NSLog(@"我教数学");  
}  
@end

我们先试验isMemberOfClass方法:

Person *person = [[Person alloc] init];  
   Teacher *teacher = [[Teacher alloc] init];  
     
   //YES  
   if ([teacher isMemberOfClass:[Teacher class]]) {  
        NSLog(@"teacher Teacher类的成员");  
   }  
   //NO  
   if ([teacher isMemberOfClass:[Person class]]) {  
       NSLog(@"teacher Person类的成员");  
   }  
   //NO  
   if ([teacher isMemberOfClass:[NSObject class]]) {  
       NSLog(@"teacher NSObject类的成员");  
   }  

打印结果:

2017-05-26 11:13:07.965 ObjectiveCTest[2460:f803] teacher Teacher类的成员

只有第一个判断打印出来,isMemberOfClass判断是否是属于这类的实例,是否跟父类有关系他不管。

 

isKindOfClass方法

Person *person = [[Person alloc] init];  
Teacher *teacher = [[Teacher alloc] init];  
  
//YES  
if ([teacher isKindOfClass:[Teacher class]]) {  
    NSLog(@"teacher 是 Teacher类或Teacher的子类");  
}  
//YES  
if ([teacher isKindOfClass:[Person class]]) {  
    NSLog(@"teacher 是 Person类或Person的子类");  
}  
//YES  
if ([teacher isKindOfClass:[NSObject class]]) {  
    NSLog(@"teacher 是 NSObject类或NSObject的子类");  
}  

打印结果:

2017-05-26 11:15:17.315 ObjectiveCTest[2595:f803] teacher 是 Teacher类或Teacher的子类
2017-05-26 11:15:17.316 ObjectiveCTest[2595:f803] teacher 是 Person类或Person的子类
2017-05-26 11:15:17.316 ObjectiveCTest[2595:f803] teacher 是 NSObject类或NSObject的子类
三个结果都打印出来了。

 

isKindOfClass和isMemberOfClass 的区别