Saran
Saran

Reputation: 6392

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

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.

Thanks.

Upvotes: 1

Views: 332

Answers (3)

Apurv
Apurv

Reputation: 17186

NSArray is a class cluster. When you create an object of NSArray, internally it creates the object from its cluster. It adds simplicity to avoid creation of different type of objects depending upon the requirements.

For such cases you should use the function isKindOfClass. It checks the completer hierarchy to identify the kind of object.

Upvotes: 2

Cameron Spickert
Cameron Spickert

Reputation: 5200

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. Typically, isKindOfClass: provides more useful results.

Upvotes: 3

Shashank
Shashank

Reputation: 1753

You should be using isKindOfClass. Refer this for the difference.

Upvotes: -1

Related Questions