Getting name of the class from an instance

69,511

Solution 1

NSStringFromClass([instance class]) should do the trick.

Solution 2

if all you want to do is test an object to see if it's a type of a certain Class

BOOL test = [self isKindOfClass:[SomeClass class]];

Solution 3

From within the class itself

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

Solution 4

OBJC:

NSStringFromClass([instance class])

SWIFT

From instance:

String(describing: YourType.self)

From type:

String(describing: self)

Solution 5

Just add a category:

NSObject+Extensions.h
- (NSString *)className;

NSObject+Extensions.m
- (NSString *)className {
    return NSStringFromClass(self.class);
}

Then use the following code:

NSString *className = [[SomeObject new] className];

or even:

NSString *className = SomeObject.new.className;

To use it anywhere add the category to YourProject.pch file.

Share:
69,511

Related videos on Youtube

Robin
Author by

Robin

Updated on December 05, 2020

Comments

  • Robin
    Robin over 3 years

    I have the following problem: I get an instance of a class passed and want to know the name of the class of this instance. How to get this?

    • Jasper Blues
      Jasper Blues over 10 years
      Perhaps reword your question or accept the answer that matches the question?
    • Robin
      Robin over 10 years
      @JasperBlues: Done, didn't even realize how popular this got!
  • Gleno
    Gleno over 10 years
    Upvoted for answering the question so that googlers can get an answer, instead of anticipating the need.
  • danh
    danh over 9 years
    Absolutely don't want to arouse your anger, but this was the second iOS-related answer in your profile. It seems to me to add only that we can refer to an instance as "self" from within its implementation. Would you defend this as adding substantially to the three-year-old accepted answer?
  • Katedral Pillon
    Katedral Pillon over 9 years
    @danh I see you are hunting me down. Good for you!
  • danh
    danh over 9 years
    Sorry, I just clicked this one, and debated about whether to say anything. Just wanted to do some gentle ribbing, but I know that tempers get hot pretty quickly in these semi-faceless settings. Thanks for being good natured about it. (In fact, +1 for practicing encapsulation).
  • Nikolai Ruhe
    Nikolai Ruhe about 9 years
    This adds nothing to the answer except trouble.
  • JP Illanes
    JP Illanes about 9 years
    Remember to #import <objc/objc-runtime.h> to able to call class on an instance.
  • jbg
    jbg over 8 years
    or just self.dynamicType
  • Bhumit Muchhadia
    Bhumit Muchhadia over 6 years
    Should make this a class method
  • Alper
    Alper over 6 years
    If called on a Swift class, this returns a namespaced classname.