challenge メソッド名一覧の表示

リフレクション系のお題の続編です。

「ある与えられたオブジェクトtargetのメソッドのうち、 "test_"で始まるものをすべて呼びだす」というコードを書いてください。 引数に関しては都合のいいように仮定して構いません(全部0個、など)。

メソッドという概念がない言語の場合は、 「複数の関数への参照を持っているようなオブジェクト(たとえばパッケージとかモジュールとか)から"test_"で始まる関数をすべて呼び出す」と読み替えても構いません。

Posted feedbacks - Objective-C


	
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#import <Foundation/Foundation.h>
#import <objc/objc-class.h>

@interface TestClass : NSObject {
}
+ (void)test_class_method;
+ (void)testClassMethod;
- (void)test_instance_method;
- (void)testInstanceMethod;
@end

@implementation TestClass
+ (void)test_class_method {
	NSLog( @"test_class_method called" );
}
+ (void)testClassMethod {
	NSLog( @"testClassMethod called" );
}
- (void)test_instance_method {
	NSLog( @"test_instance_method called" );
}
- (void)testInstanceMethod {
	NSLog( @"testInstanceMethod called" );
}
@end

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	Class cls[2] = { [TestClass class]->isa, [TestClass class] };
	TestClass* testClass = [[[TestClass alloc] init] autorelease];
	
	//forループ1回目はクラスメソッド、2回目はインスタンスメソッドの実行
	for ( int i = 0; i < 2; i++ ) {
		void* iterator = 0;
		struct objc_method_list* mlist;
		
		while ( mlist = class_nextMethodList( cls[i], &iterator ) ) {
			for ( int j = 0; j < mlist->method_count; j++ ) {
				Method method = mlist->method_list + j;
				NSString* methodName = [NSString stringWithUTF8String:(const char*)method->method_name];
				if ( [methodName hasPrefix:@"test_"] ) {
					if ( i == 0 )
						[TestClass performSelector:method->method_name];
					else
						[testClass performSelector:method->method_name];
				} else
					NSLog( @"Skip %@", methodName );
			}
		}
	}
	
    [pool release];
    return 0;
}

Index

Feed

Other

Link

Pathtraq

loading...