简体   繁体   English

isMemberOfClass的用法; 返回假

[英]usage of isMemberOfClass; returning false

In the code below I thought the second condition would be true, but it is turning out as false. 在下面的代码中,我认为第二个条件是真的,但结果却是假的。 Am I missing something? 我错过了什么吗? Please help me understand. 请帮我理解。

NSArray *array = [[NSArray alloc] init];
NSLog(@"%@", NSStringFromClass([array class]));

if ([array isMemberOfClass:[NSObject class]]) {

    NSLog(@"Member NSObject"); //Didn't print; 
}

if ([array isMemberOfClass:[NSArray class]]) {

    NSLog(@"Member NSArray"); //Didn't print; I don't understand why?
}

if ([array isKindOfClass:[NSObject class]]) {

    NSLog(@"Kind of NSObject"); //Printed; Expected
}

if ([array isKindOfClass:[NSArray class]]) {

    NSLog(@"Kind of NSArray"); //Printed; Expected
}

Edit 编辑

I created sub class of NSArray as MyArray and tested its instance using isMemberOfClass as below 我创建了NSArray的子​​类作为MyArray,并使用isMemberOfClass测试其实例,如下所示

if ([myArray isMemberOfClass:[MyArray class]]) {

    NSLog(@"Member MyArray"); //Printed;
}

So, I guess isMemberOfClass not possible on NSArray, probably on some other framework classes as well. 所以,我想isMemberOfClass在NSArray上是不可能的,也可能在其他一些框架类上。

Thanks. 谢谢。

This is the correct behavior. 这是正确的行为。 Try inspecting the actual class for that object: 尝试检查该对象的实际类:

NSArray *array = [[NSArray alloc] init];
NSLog(@"%@", NSStringFromClass([array class]));

The output you get is something like: 你得到的输出是这样的:

2013-02-15 23:42:31.272 Project[91998:c07] __NSArrayI

So the actual class is __NSArrayI (a private subclass of NSArray ), not NSArray itself. 所以实际的类是__NSArrayINSArray的私有子类),而不是NSArray本身。 Typically, isKindOfClass: provides more useful results. 通常, isKindOfClass:提供更有用的结果。

NSArray is a class cluster. NSArray是一个类集群。 When you create an object of NSArray, internally it creates the object from its cluster. 当您创建NSArray的对象时,它在内部从其集群创建对象。 It adds simplicity to avoid creation of different type of objects depending upon the requirements. 它增加了简单性,以避免根据要求创建不同类型的对象。

For such cases you should use the function isKindOfClass . 对于这种情况,您应该使用函数isKindOfClass It checks the completer hierarchy to identify the kind of object. 它检查完成者层次结构以识别对象的类型。

You should be using isKindOfClass. 你应该使用isKindOfClass。 Refer this for the difference. 请参阅差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM