views:

1109

answers:

2

Hi, I have following piece of code

NSMutableArray *mutArray = [[NSMutableArray alloc] init];
[mutArray addObject: [NSProcessInfo processInfo]];
[mutArray addObject: @"This is NSString Object"];
[mutArray addObject: [[NSMutableString alloc] initWithString: @"1st Mutable String"]];

for (id element in mutArray){
      NSLog(@" ");
      NSLog(@"Class Name: %@", [element className]);
      NSLog(@"Is Member of NSString: %@", ([element class] isMemberOfClass: [NSString class]) ? YES: NO);
      NSLog(@"Is kind of NSString: %@", ([element class] isKindOfClass: [NSString class]) ? YES: NO);
}

I am getting following output (and expecting as pointed)

Class Name: NSProcessInfo
Is Member of NSString: NO
Is Kind of NSString: NO

Class Name: NSCFString         <-- Expecting NSString
Is Member of NSString: NO      <-- Expecting YES
Is Kind of NSString: NO        <-- Expecting YES

Class Name: NSCFString         <-- Expecting NSMutableString
Is Member of NSString: NO      
Is Kind of NSString: NO        <-- Expecting YES

Am I missing something terrible simple here? Thanks!

+1  A: 

NSString is made up of a cluster of classes. They are also toll-free-bridged with CFStrings (from CoreFoundation). It's very likely somewhere in the implementation of NSString this NSCFString appears (I don't know all the facts, but my deduction here is this class acts as the bridge).

jbrennan
So if we want to do any instrospection, should we be really checking against NSCFString?
Dev
i.e. for NSString and NSMutableString class objects?
Dev
+6  A: 

Use:

[element isMemberOfClass: [NSString class]]

Not:

[[element class] isMemberOfClass: [NSString class]]

NSString and NSMutableString are implemented as a class cluster (see "String Objects" in the iPhone version of the documentation).

So isKindOfClass: should return true but isMemberOfClass: will return false since NSString isn't the exact type of the object.

dmercredi
nice catch :) ... thanks!
Dev