views:

58

answers:

3

I have just been watching the Stanford iPhone lecture online from Jan 2010 and I noticed that the guy from Apple keeps referring to getting an objects class name using "className" e.g.

NSArray *myArray = [NSArray arrayWithObjects:@"ONE", @"TWO", nil];
NSLog(@"I am an %@ and have %d items", [myArray className], [myArray count]);

However, I can't get this to work, the closest I can come up with it to use class, is className wrong, did it get removed, just curious?

NSArray *myArray = [NSArray arrayWithObjects:@"ONE", @"TWO", nil];
NSLog(@"I am an %@ and have %d items", [myArray class], [myArray count]);

Gary

+3  A: 

The className method is only available on Mac OS X, not on iPhoneOS. It is usually used for scripting support, which is why it doesn't exist on the iPhone. You can use something like:

NSString* className = NSStringFromClass([myArray class]);

If you want to store the string. NSStringFromClass() isn't strictly necessary, but you should probably use it as it's the "documented" way to do things.

Jason Coco
Thank you, I was more curious as it kept getting mentioned and yet when I tried it in a basic iPhone app I got an error, I see whats happening now.
fuzzygoat
+2  A: 

The className method only exists on the Mac. However, it's fairly easy to implement for iPhone via an NSObject category:

//NSObject+ClassName.h
@interface NSObject (ClassName)

- (NSString *) className;

@end

//NSObject+ClassName.m
@implementation NSObject (ClassName)

- (NSString *) className {
  return NSStringFromClass([self class]);
}

@end

Now every NSObject (and subclass) in your application will have a className method.

Dave DeLong
A: 
NSStringFromClass( [someObject class] );

and before Objective-C 2.0

someObject->isa.name
drawnonward