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?
-
Perhaps reword your question or accept the answer that matches the question?Jasper Blues– Jasper Blues2013-11-07 12:33:36 +00:00Commented Nov 7, 2013 at 12:33
-
@JasperBlues: Done, didn't even realize how popular this got!Robin– Robin2013-11-07 16:05:42 +00:00Commented Nov 7, 2013 at 16:05
Add a comment
|
8 Answers
NSStringFromClass([instance class]) should do the trick.
2 Comments
Gleno
Upvoted for answering the question so that googlers can get an answer, instead of anticipating the need.
JP Illanes
Remember to
#import <objc/objc-runtime.h> to able to call class on an instance.From within the class itself
-(NSString *) className
{
return NSStringFromClass([self class]);
}
5 Comments
danh
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
@danh I see you are hunting me down. Good for you!
danh
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
This adds nothing to the answer except trouble.
Bhumit Muchhadia
Should make this a class method
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.
1 Comment
Alper
If called on a Swift class, this returns a namespaced classname.
If you are looking how get classname in Swift you can use reflect to get information about object.
let tokens = split(reflect(self).summary, { $0 == "." })
if let typeName = tokens.last {
println(typeName)
}
1 Comment
jbg
or just
self.dynamicType- for instance
NSString* classNameNSStr = [someObjcInstance className]
- for class
NSString* classNameNSStr = NSStringFromClass(someObjcClass)const char* className = object_getClassName(someObjcClass)
--> related:
- just want compare is some class or not
- -> not need get class name, just need use
isKindOfClass:BOOL isSameClass = [someObjcInstance isKindOfClass: SomeClass];SomeClasscan get from:objc_getClass("SomeClassName")
- -> not need get class name, just need use