8

Is there a quick way to use some sort of typeof() equivalent in Objective-C? In Javascript I can type:

var a = "imastring";
console.log(typeof(a));
// --> "string"

I would like something clean in Objective-C that isn't a compiler directive.

Ichigo Kurosaki
  • 317
  • 2
  • 12
  • possible duplicate of [In Objective-C, given an id, how can I tell what type of object it points to?](http://stackoverflow.com/questions/1123485/in-objective-c-given-an-id-how-can-i-tell-what-type-of-object-it-points-to) – Almo Sep 12 '14 at 00:09
  • Naturally you're asking about object types only? Or would a discussion of GCC's `typeof` extension and/or what Objective-C does to create signatures for non-object types be helpful? – Tommy Sep 12 '14 at 00:16
  • @Tommy, actually, I would love a discussion on this topic. I don't know much about the best practices, since I am coming to Objective-C from Javascript, and since it seems I shouldn't use the [object class] in the same way in obj-c as I would in javascript, it would be great to know why, so I can shift my way of thinking. – Ichigo Kurosaki Sep 12 '14 at 00:24

2 Answers2

13

Yes, you can use the [object class] method:

NSArray *a = @[@"a", @"b"];
NSLog(@"NSArray = %@", [a class]);
// NSArray = __NSArrayI

NSMutableArray *b = [[NSMutableArray alloc] initWithArray:a];
NSLog(@"NSMutableArray = %@", [b class]);
// NSMutableArray = __NSArrayM

NSString *c = @"imastring";
NSLog(@"NSString = %@", [c class]);
// NSString = __NSCFConstantString

NSNumber *d = [[NSNumber alloc] initWithInteger:5];
NSLog(@"NSNumber = %@", [d class]);
// NSNumber = __NSCFNumber

Keep in mind that is is common to see the __NSCF or the __NS prefix on most of the objects you inspect in this manner. For example, when logging the class type of an NSString, you are likely to see __NSCFString or __NSCFConstantString (which are both NSString types) as the result. I only ever use this approach when I am curious to see how things look behind the scenes, but I don't tend to use this type of check in production.

You can look into using the isKindOfClass method to test if the object is a certain type.

radiovisual
  • 6,298
  • 1
  • 26
  • 41
  • 2
    Props for mentioning `-isKindOfClass:`; don't do identity comparisons on `class` even though metaclasses are unique — that won't properly allow for subclasses, and the concept of class clusters means that often in Objective-C you're handling a subclass even though you don't realise it. – Tommy Sep 12 '14 at 00:14
  • This worked for me, but I did get the __NSCF and __NS prefixes you mentioned, so now it makes me wonder if there is something I am missing, and if I should be checking for object equality or doing object comparisons in another way? – Ichigo Kurosaki Sep 12 '14 at 00:26
3

You can use the class method of NSObject.

Ben-G
  • 4,996
  • 27
  • 33