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.
Related videos on Youtube
Author by
Robin
Updated on December 05, 2020Comments
-
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 over 10 yearsPerhaps reword your question or accept the answer that matches the question?
-
Robin over 10 years@JasperBlues: Done, didn't even realize how popular this got!
-
-
Gleno over 10 yearsUpvoted for answering the question so that googlers can get an answer, instead of anticipating the need.
-
danh over 9 yearsAbsolutely 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 over 9 years@danh I see you are hunting me down. Good for you!
-
danh over 9 yearsSorry, 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 about 9 yearsThis adds nothing to the answer except trouble.
-
JP Illanes about 9 yearsRemember to
#import <objc/objc-runtime.h>
to able to call class on an instance. -
jbg over 8 yearsor just
self.dynamicType
-
Bhumit Muchhadia over 6 yearsShould make this a class method
-
Alper over 6 yearsIf called on a Swift class, this returns a namespaced classname.