Question

I know in Objective-C we can get a class type for an object using:

+ (Class)class;

However, if I want to get the class type for primitive types, like int or short, how do I do that?

Does something like that exist in Objective C?

In Java we can get the class types of primitives by following: E.g. Class<?> classType = short.class;

Does anything similar exist in Objective C?

NSString* numStr = @"124";

Now I want to dynamically invoke a method (the method name is known at runtime only). The method could take any type of numeric input like short, int, long, double, or NSNumber.

E.g.

(void) doSomethingWithInt: (int) intVal;
(void) doSomethingWithShort: (short) shortVal;
(void) doSomethingWithDouble: (double) doubleVal;
(void) doSomethingWithNSNum: (NSNumber) NSNumVal;

I believe NSInvocation can be used for invoking methods reflectively. But while setting arguments in the NSInvocation, object how can I properly convert the string to all the different types?

Was it helpful?

Solution

Primitives are not classes, thus you can't get their type like this. However, there's @encode (see also the NSHipster blog entry) which might be of help to you, depending on what you want to do.

In Java primitives aren't classes either, but through autoboxing the corresponding wrapper classes are used when necessary. Objective-C doesn't do this magic for you.

To solve the usecase: Assuming the function takes only primitive numeric values or NSNumber we can identify the right parameter type using @encoding as described in the comment. There is no other way to reflectively identify the exact method signature.

OTHER TIPS

Primitives don't have classes, by definition, but you can use the __typeof__ keyword to get the type of a primitive, even using it to declare another variable with that type:

int x = 10;
__typeof__(x) y = 12;

However if I want to get the class type for primitive types like int or short how do I do it?

int, char, float etc are not a class.

However you can get its type by objective-C runtime.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top