- [NSObject isMemberOfClass:]方法有多有用? [英] How useful is the -[NSObject isMemberOfClass:] method?

查看:229
本文介绍了 - [NSObject isMemberOfClass:]方法有多有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个我写的小测试程序:

Here's a small test program I wrote:

#import <Foundation/Foundation.h>

int main(int argc, char **argv) {   
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSArray *arr = [NSArray array];
    printf("Arr isMemberOfClass NSArray: %d\n", [arr isMemberOfClass:[NSArray class]]);
    printf("Arr isKindOfClass NSArray: %d\n", [arr isKindOfClass:[NSArray class]]); 

    [pool release];
    return 0;
}  

及其输出:

$ ./ismemberof   
Arr isMemberOfClass NSArray: 0   
Arr isKindOfClass NSArray: 1   

-isMemberOfClass:方法在任何Foundation类中有多有用?我理解这可能给我想要的类的类,我的子类,但对于Foundation类 - 我发现,对我的arr变量的结果是非直观的。这是因为NSArray不是一个具体的类,而是一个抽象类,而在下面的NSArray是真正的NSCFArray的具体实例。

How useful is the -isMemberOfClass: method in any of the Foundation classes? I understand this might give the desired results for classes which I subclass, but as for Foundation classes -- I find that a result of false for my arr variable is non-intuitive. Is the reason this happens because NSArray is not a concrete class but instead an abstract class, and underneath the hood NSArray is really a concrete instance of NSCFArray?

推荐答案

您通常需要 isKindOfClass:,而不是 isMemberOfClass:。区别是 isKindOfClass:将返回 YES 如果接收者是有问题类的子类的成员, isMemberOfClass:将在同一个案例中返回 NO

You generally want isKindOfClass:, not isMemberOfClass:. The difference is that isKindOfClass: will return YES if the receiver is a member of a subclass of the class in question, whereas isMemberOfClass: will return NO in the same case.

As Graham Lee指出, NSArray 是一个类集群。这意味着每个 NSArray 实例实际上是一个子类的实例 - 因此你的发现。只有 isKindOfClass:对于具有类集群的类成员测试很有用。

As Graham Lee points out, NSArray is a class cluster. That means that every NSArray instance is actually an instance of some subclass—hence your findings. Only isKindOfClass: is useful for class-membership testing with class clusters.

code> respondingToSelector:而不是类成员测试。一个例子是 objectEnumerator ,它也由 NSSet NSDictionary (两者都是类集群)。一个例外是plist serialization:sets不是属性列表,所以你需要发送 allObjects 到你的集合,以获取一个数组,然后试图从它的plist数据。

That said, you generally should use respondsToSelector: rather than class-membership testing. One example would be objectEnumerator, which is also implemented by NSSet and NSDictionary (both of those also being class clusters). An exception would be plist serialization: sets aren't property lists, so you'd need to send allObjects to your set to get an array before trying to make plist data from it.

这篇关于 - [NSObject isMemberOfClass:]方法有多有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆