Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 659
Coocoo4Cocoa Avatar asked Dec 21 '08 01:12

Coocoo4Cocoa


1 Answers

The -isMemberOfClass: is useful when you're implementing the -isEqual: method in your own classes. If you have a class like this:

@interface Person : NSObject {
    NSString *name;
    NSUInteger age;
}
@property(copy) NSString *name;
@property(assign) NSUInteger age;
@end

And you want two Person objects to be deemed identical if they have the same name and age, you have to implement -isEqual:, and the -hash method from the NSObject protocol:

- (BOOL)isEqual:(id)obj {
    return [obj isMemberOfClass:[self class]]
        && [obj name] == self.name
        && [obj age] == self.age;
}

- (NSUInteger)hash {
    return [self.name hash] + age;
}

PS: why use [obj isMemberOfClass:[self class]] rather than simply [obj class] == [self class]? It doesn't matter much in the code above, but it becomes important when you're dealing with more complex code that makes use of NSProxy. The isMemberOfClass: method will ask the object the proxy is standing in for if it is a member of that class, which is probably what you want.

like image 188
Stig Brautaset Avatar answered Nov 09 '22 01:11

Stig Brautaset