Jochen
Jochen

Reputation: 7531

Getting type encodings for method signatures in Cocoa/Objective-C?

I need to construct an arbitrary NSMethodSignature with "signatureWithObjCTypes:" in Cocoa without having an object that I can ask for a signature with "methodSignatureForSelector:".

For this, I need the method encoding, which e.g. is

c12@0:4@8

for

(BOOL) isEqual: (id) object

I tried @encode(...) to obtain a type encoding, but this does not seem to work for functions (it results in an unknown type '?'). I dont't want to manually encode the function type, since this is not portable across different runtimes.

There also is no declared method to obtain the encoding from.

Is there another way of obtaining the encoding?

Regards,

Jochen

Upvotes: 6

Views: 2254

Answers (2)

Dave DeLong
Dave DeLong

Reputation: 243156

What about something like:

#import <objc/runtime.h>
//inside the method implementation:
Method thisMethod = class_getClassMethod([self class], _cmd);
const char * encoding = method_getTypeEncoding(thisMethod);

Or for an arbitrary method:

#import <objc/runtime.h>
//inside the method implementation:
Method thisMethod = class_getClassMethod([self class], @selector(isEqual:));
const char * encoding = method_getTypeEncoding(thisMethod);

Upvotes: 12

Georg Sch&#246;lly
Georg Sch&#246;lly

Reputation: 126135

Doesn't it just work using the unknown type encoding?

? | An unknown type (among other things, this code is used for function pointers)

AFAIK it shouldn't matter because it's just about the size of the argument. Function pointers have the same size as the standard argument which is an int.

Upvotes: 0

Related Questions