Search code examples
objective-cintrospectionobjective-c-runtime

Is there a way to get the parameter's class type from a Method struct?


There is a method like this.

- (void)method: (CustomClass)param;

CustomClass inherits from NSObject.

I have a variable m below, which is the Method struct for that method. I invoked method_getArgumentType() to get the argument types like this:

char szArgType[100] = {0,};
Method m = ...;
...
method_getArgumentType(m, 2, szArgType, 100);

I printed szArgType. It printed @, but I want to print CustomClass. Is there a good way to get the real object class type for a parameter from a Method at runtime?


Solution

  • It is not possible to do this. The interface type (the class) is used only by the compiler, and it does not preserve that information when it encodes the method signature.

    The only information you can get at runtime is what's described in the Type Encodings chapter of the Runtime Guide, which is whether the parameter is an object as opposed to any of the various POD types. The encoding for any object will be the same no matter its class, the @ that you see there. (Essentially, everything is an id after the compiler is done with its type checking.)