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. (required)

isMemberOfClass

Returns a Boolean value that indicates whether the receiver is an instance of a given class. (required)

相同点:

都是NSObject的比较Class的方法

不同点:

1. isKindOfClass是确定一个对象是否是一个类的成员,或者是派生自该类的成员。

2. isMemberOfClass只能确定一个对象是否是一个类的的成员。

特殊情况:

官方文档

Be careful when using this method on objects represented by a class cluster. Because of the nature of class clusters, the object you get back may not always be the type you expected. If you call a method that returns a class cluster, the exact type returned by the method is the best indicator of what you can do with that object. For example, if a method returns a pointer to an NSArray object, you should not use this method to see if the array is mutable, as shown in the following code:

// DO NOT DO THIS!

if ([myArray isKindOfClass:[NSMutableArray class]]) {

// Modify the object

}

If you use such constructs in your code, you might think it is alright to modify an object that in reality should not be modified. Doing so might then create problems for other code that expected the object to remain unchanged.

If the receiver is a class object, this method returns YES if aClass is a Class object of the same type, NO otherwise.

测试如下

测试如下

NSArray*myArr = [[NSArrayalloc] init];

NSMutableArray*myArr2 = [[NSMutableArrayalloc] init];

if([myArr isKindOfClass:[NSArrayclass]]) {

NSlog(@"myArr isKindOfClass of NSArray");}

if([myArr isMemberOfClass:[NSArrayclass]]) {

NSlog(@"myArr isMemberOfClass of NSArray");

}

if([myArr2 isKindOfClass:[NSMutableArrayclass]]) {

NSlog(@"myArr2 isKindOfClass of NSMutableArray");}

if([myArr2 isMemberOfClass:[NSMutableArrayclass]]) {

NSlog(@"myArr2 isMemberOfClass of NSMutableArray");

}

输出结果:

myArr isKindOfClass ofNSArray

myArr2 isKindOfClass ofNSMutableArray

总结如下:

1、NSArray、NSMutableArray属于类簇,使用isMemberOfClass不能得到正确的结果,因为由于类簇的性质,这类对象实际返回的实例有不确定性。

2、对于类簇的判断要谨慎。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,757评论 0 9
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,797评论 0 23
  • 明天泉州首期SEL亲子营开班了,下午和伙伴一起去布置现场,原以为40分钟左右就可以布置好,没想到布置了三...
    Alice林阅读 258评论 0 0
  • 我猜 你喜欢蒙古的大草原 一望无际, 天苍苍,野茫茫,风吹草低现牛羊 我猜 你喜欢戈壁滩大沙漠 浩瀚无边 大漠孤烟...
    凡高潇湘花子阅读 426评论 0 4
  • 1920年10月,在剑桥大学留学的徐志摩,见到了与父亲一起住在伦敦的林徽因。此年,徐23岁,林16岁,还是个邻家有...
    马风阅读 2,394评论 26 57