isMemberOfClass,isKindOfClass的用法!

qq_28334193 2015-08-28 07:52:25
NSArray *arr5 = [NSArray new];
NSLog(@"arr5 retainCount:%lu",[arr5 retainCount]);
NSArray *arr6 = [arr5 mutableCopy];


if ([arr6 isKindOfClass:[NSMutableArray class]])
{
NSLog(@"arr6 is mutable");
NSMutableArray *marr6 = (NSMutableArray *)arr6;
[marr6 addObject:@"abc"];
NSLog(@"marr6:%@",marr6);
}


这句中 if ([arr6 isKindOfClass:[NSMutableArray class]]),arr6不是属于NSArray 吗? NSArray 又是NSMutableArray 的父类,isKindOfClass不是判断arr6实例是不是属于NSMutableArray 这个类或者是这个类的子类吗? 为什么我([arr6 isKindOfClass:[NSMutableArray class]]为1,[arr6 isMemberOfClass:[NSMutableArray class]]和[arr6 isMemberOfClass:[NSMutableArray class]]都为0

请解释一下isMemberOfClass,isKindOfClass的用法。还有[A isKindOfClass:[B class]],A一定是要实例吗,B一定是要类吗?


...全文
489 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_28334193 2015-08-30
  • 打赏
  • 举报
回复
还是不懂啊!!
CJoneL 2015-08-29
  • 打赏
  • 举报
回复
-(BOOL) isKindOfClass: classObj判断是否是这个类或者这个类的子类的实例 -(BOOL) isMemberOfClass: classObj 判断是否是这个类的实例
不担心 2015-08-28
  • 打赏
  • 举报
回复
这个官方文档已经解释的很清楚了 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) 至于你那个if ([arr6 isKindOfClass:[NSMutableArray 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.

29,027

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧