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.

Discussion

For example, in this code, isKindOfClass: would return YES because, in Foundation, the NSArchiver class inherits from NSCoder:

NSMutableData *myData = [NSMutableData dataWithCapacity:30];

id anArchiver = [[NSArchiver alloc] initForWritingWithMutableData:myData];

if ( [anArchiver isKindOfClass:[NSCoder class]] )

...

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.

- isMemberOfClass:

仅用以判断某个对象是不是给出类的实例对象。

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

Discussion

For example, in this code, isMemberOfClass: would return NO:

NSMutableData *myData = [NSMutableData dataWithCapacity:30];

id anArchiver = [[NSArchiver alloc] initForWritingWithMutableData:myData];

if ([anArchiver isMemberOfClass:[NSCoder class]])

...

Class objects may be compiler-created objects but they still support the concept of membership. Thus, you can use this method to verify that the receiver is a specific Class object.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 14,599评论 5 6
  • 小表妹要去上大学了,印象里的小孩也有上大学的一天,曾经物理化学考30分的人,竟然也长大了,结果还是没上一本线,只好...
    名贝贝阅读 3,749评论 3 5
  • 最初看到电影名字《地心营救》,下意识认为又是和《2012》、《后天》等一样的惊险灾难场面电影,准备要来一场虚拟惊险...
    stone_thinker阅读 6,537评论 2 1
  • 别笑着面对一切 低下头来 看着无力的双脚 还有那 徘徊不前的足迹 一阵沉默 一阵思考 留下的只是难言的叹息 你说过...
    月桥居士阅读 2,750评论 0 0

友情链接更多精彩内容