Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

objective c - How useful is the -[NSObject isMemberOfClass:] method?

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
", [arr isMemberOfClass:[NSArray class]]);
    printf("Arr isKindOfClass NSArray: %d
", [arr isKindOfClass:[NSArray class]]); 

    [pool release];
    return 0;
}  

And its output:

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...