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

后端 未结 3 1096
说谎
说谎 2020-12-09 06:12

Here\'s a small test program I wrote:

#import 

int main(int argc, char **argv) {   
    NSAutoreleasePool *pool = [[NSAutorel         


        
3条回答
  •  醉酒成梦
    2020-12-09 06:30

    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.

提交回复
热议问题