tags:

views:

45

answers:

2

Hi all, Is it possible to get the name of a class into a string like this:

NSString *kls = (NSString *)[self.name class];
NSLog(@"%@", [kls isKindOfClass:[NSString class]] ? @"YES" : @"NO");

I can do: NSString *kls = [[[NSString alloc]initWithFormat:@"%@", [self.name class]]autorelease];

but that seems a bit long-winded to me. It's not for any task in particular, I'm just trying to learn more about the language as I go.

thanks for reading.

A: 

On the Mac, provided your object inherits from the NSObject class rather than just implementing the NSObject protocol (the latter situation seems sort of unlikely), you should be able to call:

NSString* str = [anObject className];

className is defined in connection with Mac scripting support, so it is not available on the iOS version of NSObject. In that case, you can probably do something like this:

NSString* str = [[anObject class] description];

(I have only actually tried this on a Mac, though, so it's possible it may not work correctly on an iOS device.)

walkytalky
Don't use the -description method in production code. For debugging? Sure. Use `NSStringFromClass()`.
bbum
@bbum I'm not about to argue with the mighty bbum, but I am curious: do you mean that -description may legitimately fail or produce strange results at runtime? And that's expected? It seems kind of perverse if so.
walkytalky
Oh, hell, please.. argue with me if I'm wrong. :) `-description` is defined to be, more or less, a "runtime description of the object". It will sometimes -- more rarely for some objects than others -- change over time to provide a better runtime description. `NSStringFromClass()` and `NSClassFromString()` are explicitly designed to be bidirectional conversion conduit for classes / class names.
bbum
A: 

NSString* classNameStr = NSStringFromClass( [anObject class] );

progrmr