Obtener el nombre de la clase de una instancia


Tengo el siguiente problema: me pasa una instancia de una clase y quiero saber el nombre de la clase de esta instancia. Cómo conseguir esto?

Author: ROMANIA_engineer, 2010-02-07

6 answers

NSStringFromClass([instance class]) debería funcionar.

 354
Author: CiNN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-07 17:33:17

Si todo lo que desea hacer es probar un objeto para ver si es un tipo de cierta Clase

BOOL test = [self isKindOfClass:[SomeClass class]];
 26
Author: kubi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-07 17:39:53

Desde dentro de la propia clase

-(NSString *) className
{
    return NSStringFromClass([self class]);
}
 16
Author: Katedral Pillon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-13 05:42:51

Simplemente agregue una categoría:

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

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

Luego use el siguiente código:

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

O incluso:

NSString *className = SomeObject.new.className;

Para usarlo en cualquier lugar, agregue la categoría a YourProject.archivo pch.

 2
Author: ealee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-13 10:44:52

También puedes usar [[self class] description]

 1
Author: Jeremie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-07 16:59:42

Si está buscando cómo obtener classname en Swift, puede usar reflect para obtener información sobre object.

let tokens = split(reflect(self).summary, { $0 == "." })
if let typeName = tokens.last {
    println(typeName)
}
 0
Author: Roman Barzyczak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-29 00:47:07