Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

className and isKindOfClass messages sent to an object

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!

like image 243
Dev Avatar asked Aug 13 '09 03:08

Dev


2 Answers

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 iOS version of the documentation).

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

like image 123
dmercredi Avatar answered Oct 13 '22 19:10

dmercredi


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

like image 2
jbrennan Avatar answered Oct 13 '22 18:10

jbrennan