美文网首页
isKindOfClass,isMemberOfClass,is

isKindOfClass,isMemberOfClass,is

作者: LvBean | 来源:发表于2017-11-13 10:05 被阅读21次

    今天突然被问到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。

    摘抄字作者:qilinit

    链接:http://www.jianshu.com/p/235a65e96ac8

    來源:简书

    相关文章

      网友评论

          本文标题:isKindOfClass,isMemberOfClass,is

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