Type encoding string for protocol method

954 views Asked by At

I'm trying to get a signature -- either an NSMethodSignature object or at least the type encoding string -- for a method declared in a protocol.

Asking the Protocol object itself isn't possible, since a) it doesn't implement methodSignatureForSelector:, and b) (as noted by Kevin below) it's deprecated.

The runtime function protocol_getMethodDescription returns a struct objc_method_description, which isn't described anywhere in the docs. It's in a public header, though -- <objc/runtime.h>:

struct objc_method_description {
    SEL name;
    char *types;
};

It seems reasonable to assume that the types string in there is going to be the same kind of signature encoding string used elsewhere, such as that expected by +[NSMethodSignature signatureWithObjCTypes:], and indeed, it looks correct.

What I can't track down is an actual, verifiable connection between that string and the type encoding process.

I can't think what else it would be, but still, do I have any justification for relying on this types string to be valid for interaction with other objects/functions on the same runtime? Note that I'm not writing encoding strings myself or expecting them to have a given format or value -- I only want to pass them from one part of the runtime/framework to another, i.e., retrieve an encoding string from a protocol and a) use it to generate an NSMethodSignature object if one isn't otherwise available, and possibly b) compare it to that of a runtime-generated NSInvocation (i.e., in -forwardInvocation:).

1

There are 1 answers

2
Lily Ballard On BEST ANSWER

Using Protocol as an object is deprecated. If you check the header <objc/Protocol.h> you'll see that pretty much everything on it is either not available in OBJC-2 or is deprecated as of OS X 10.5. What you can do is use protocol_getMethodDescription(), as you suggested, and pull out the types field. I'm not sure if it's actually officially documented that this is the type encoding of the method, but that is indeed what it is.