views:

183

answers:

3

When I send an object to NSLog, I get a string with three attributes. First is the class of the object, second is the frame of the object, and third is the CALayer of the object. The second and third attributes are titled (e.g. layer = ), so I can call them by the title (e.g. myObject.layer).

The first one isn't. How do I test for the class type?

Thanks!

+6  A: 

To get the class of an object, simply call [myObject class]. You can compare this to a desired class as follows:

if ([myObject class] == [SomeClass class]) { /* ... */ }
if ([myObject class] == [NSString class]) { /* ... */ }

If you are simply looking for the class name as a string, you can use the NSStringFromClass function as follows:

NSString * className = NSStringFromClass([myObject class]);
e.James
Thanks so much. That's exactly what I needed.
Eric Christensen
You're welcome :)
e.James
+5  A: 

If you also want to include subclasses of targeted class use:

[object isKindOfClass:[SomeClass class]]
Diederik Hoogenboom
Thanks. You guys are awesome!
Eric Christensen
@Diederik Hoogenboom: Good point. I forgot about that one!
e.James
+1  A: 

@eJames and @Diederik are both correct. However, there are a few other options, some of which may be preferable depending on your taste.

For example, instead of testing for equality of class objects, you can also use -isMemberOfClass: which excludes subclasses, whereas -isKindOfClass: and -isSubclassOfClass: do not. (This is definitely a case where one option may be more intuitive for some people than for others.)

Also, [SomeClass className] or [anObject className] are convenient, shorter ways to get the class name as an NSString. (I know -className is defined on NSObject, and +className works for class prototypes, although I can't find the documentation for it readily.)

Quinn Taylor