isKindOfClass,isMemberOfClass,isSubclassOfClass的区别

今天突然被问到isKindOfClass,isMemberOfClass的区别,瞬间懵了,虽然是知道根据类的名称判断是否属于这个类,但没有具体的了解,总归问到的时候不能回答 ”用的时候看心情吧0.0“,就区别了一下,其实也很简单

 以下的类层次是这样的,BaseZombie是所有僵尸类的基类,ZombieType1是继承于BaseZombie的一个类,textType是继承于ZomboeType1的类
@interface BaseZombie : NSObject
@interface ZombieType1 : BaseZombie
@interface textType1 : ZombieType1//失误了,记得类名开头大写
 首先看一下开发文档中描述isKindOfClass
- (BOOL)isKindOfClass:(Class)aClass
Description 
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. (required)

//意思是返回一个BOOL类型的值,表示调用该方法的类 是否是 参数类 或者 继承于参数类

通过程序来反馈下结果会更加的明显,

textType1 * text1 = [[textType1 alloc]init];//初始化一个测试子类
        
BOOL b1 = [text1 isKindOfClass:[textType1 class]];//YES
BOOL b2 = [text1 isKindOfClass:[ZombieType1 class]];//YES
  接下来看一下开发文档中的描述isMemberOfClass
- (BOOL)isMemberOfClass:(Class)aClass
Description 
Returns a Boolean value that indicates whether the receiver is an instance of a given class. (required)

//意思是返回一个BOOL类型的值,表示调用该方法的类 是否是 参数类

通过程序反馈结果如下

BOOL b3 = [text1 isMemberOfClass:[textType1 class]];//YES
BOOL b4 = [text1 isMemberOfClass:[ZombieType1 class]];//NO 父类不被承认
    最后一个是开发文档中的isSubclassOfClass

//注意这是一个类方法

+ (BOOL)isSubclassOfClass:(Class)aClass
Description 
Returns a Boolean value that indicates whether the receiving class is a subclass of, or identical to, a given class.

//意思是返回一个BOOL类型的值,表示调用该方法的类 是不是 参数类的一个子类 或者 是这个类的本身

程序反馈如下

BOOL b5 = [textType1 isSubclassOfClass:[ZombieType1 class]];//YES
BOOL b6 = [textType1 isSubclassOfClass:[textType1 class]];//YES
BOOL b7 = [textType1 isSubclassOfClass:[NSString class]];//NO
   综上看来,isSubclassOfClass和isKindOfClass的作用基本上是一致的,只不过一个是类方法,一个是对象方法。
   isMemberOfClass 筛选条件更为苛刻,只有当类型完全匹配的时候才会返回YES。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,123评论 6 13
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,869评论 18 139
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,205评论 30 471
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,762评论 0 9
  • 本笔记为GeekBand C++面向对象高级编程(上)第一周课程之总结。 本周主要内容涉及: -- 头文件与类的...
    Yuxuanxuan阅读 191评论 0 1