How to get a list of the methods from an object?

Friday, November 07 2003 @ 10:01 PM UTC

Contributed by: cocoa

I need the names and argument lists of of some methods of a specific class…

Here is some example code:


#import <Cocoa/Cocoa.h>
#import <stdio.h>
#import <objc/objc.h>
#import <objc/objc-runtime.h>


@interface TestClass : NSObject
{
}

- (id)method1:(id)inObject boolean:(BOOL)inBoolean;
- (id)method2:(id)inObject ints:(int)inInt1,...;

@end

@implementation TestClass
- (id)method1:(id)inObject boolean:(BOOL)inBoolean
{
	return nil;
}

- (id)method2:(id)inObject ints:(int)inInt1,...
{ 
	return nil ;
}

@end

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

	Class  aClass = objc_getClass("TestClass")  ;
	
	while (aClass) {
		void *iterator = 0	;
		struct objc_method_list *list = class_nextMethodList(aClass,&iterator)  ;
		
		while (list != nil) {
			int i   ;
			
			for(i=0;imethod_count;i++)   {
				printf("%s %sn",list->method_list[i].method_name,list->method_list[i].method_types);
			}
			list = class_nextMethodList(aClass,&iterator)  ;
		}
		aClass = aClass->super_class	;
	}

    [pool release];
    return 0;
}

The output is:

method2:ints: @16@0:4@8i12
method1:boolean: @16@0:4@8c12
_conformsToProtocolNamed: c12@0:4r*8
replacementObjectForPortCoder: @12@0:4@8
classForPortCoder #8@0:4
inverseForRelationshipKey: @12@0:4@8
toManyRelationshipKeys @8@0:4
toOneRelationshipKeys @8@0:4
attributeKeys @8@0:4
classDescription @8@0:4
...
As you see the main job to be done is to "decode" the string defining the parameters. You will find more information in the Objective-C documentation.

0 comments



http://www.macosxguru.net/article.php?story=20031107220157892