Getting name of the class from an instance

IphoneObjective CClassInstanceClassname

Iphone Problem Overview


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?

Iphone Solutions


Solution 1 - Iphone

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

Solution 2 - Iphone

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 - Iphone

From within the class itself

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

Solution 4 - Iphone

OBJC:

NSStringFromClass([instance class])

SWIFT

From instance:

String(describing: YourType.self)

From type:

String(describing: self)

Solution 5 - Iphone

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.

Solution 6 - Iphone

You can also use [[self class] description]

Solution 7 - Iphone

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)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobinView Question on Stackoverflow
Solution 1 - IphoneCiNNView Answer on Stackoverflow
Solution 2 - IphonekubiView Answer on Stackoverflow
Solution 3 - IphoneKatedral PillonView Answer on Stackoverflow
Solution 4 - IphoneLal KrishnaView Answer on Stackoverflow
Solution 5 - IphoneealeeView Answer on Stackoverflow
Solution 6 - IphoneJeremie DView Answer on Stackoverflow
Solution 7 - IphoneRoman BarzyczakView Answer on Stackoverflow