Robin
Robin

Reputation: 8357

Getting name of the class from an instance

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?

Upvotes: 152

Views: 74844

Answers (8)

crifan
crifan

Reputation: 14338

  • 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];
        • SomeClass can get from: objc_getClass("SomeClassName")

Upvotes: 0

Lal Krishna
Lal Krishna

Reputation: 16190

OBJC:

NSStringFromClass([instance class])

SWIFT

From instance:

String(describing: YourType.self)

From type:

String(describing: self)

Upvotes: 5

ealee
ealee

Reputation: 91

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.

Upvotes: 2

Roman Barzyczak
Roman Barzyczak

Reputation: 3813

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

Upvotes: 1

Jeremie D
Jeremie D

Reputation: 4204

You can also use [[self class] description]

Upvotes: 2

Katedral Pillon
Katedral Pillon

Reputation: 14864

From within the class itself

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

Upvotes: 17

kubi
kubi

Reputation: 49394

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]];

Upvotes: 31

CiNN
CiNN

Reputation: 9880

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

Upvotes: 416

Related Questions