Created
March 26, 2012 04:31
-
-
Save mazgi/2202939 to your computer and use it in GitHub Desktop.
NSInvocationを使ってメッセージ送信するサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
/*! | |
@header | |
@abstract NSInvocationを使ってメッセージ送信するサンプル | |
@disucussion Cocoaじゃないと動かないと思います | |
*/ | |
@interface TestObj : NSObject | |
- (void)run; | |
- (BOOL)foo:(BOOL)value; | |
@end | |
@implementation TestObj | |
/*! | |
@method | |
@abstract 呼び出されるサンプルメソッド | |
*/ | |
- (BOOL)foo:(BOOL)value | |
{ | |
NSLog(@"value=>%d", value); | |
return value; | |
} | |
/*! | |
@method | |
@abstract NSInvocationを使用してメッセージ送信を行うメソッド | |
*/ | |
- (void)run | |
{ | |
//メッセージを送信したいオブジェクト | |
id const kInstance=self; | |
//呼び出したいメソッド | |
const SEL kSelector=@selector(foo:); | |
//メソッドに渡したい最初の引数 | |
BOOL arg2Buff=YES; | |
//メソッドから受け取りたい戻り値 | |
BOOL result=NO; | |
NSLog(@"result=>%d", result); | |
if ([kInstance respondsToSelector:kSelector]) { | |
NSMethodSignature *signature=[[kInstance class]instanceMethodSignatureForSelector:kSelector]; | |
NSInvocation *invocation=[NSInvocation invocationWithMethodSignature:signature]; | |
[invocation setTarget:kInstance]; | |
[invocation setSelector:kSelector]; | |
//0番目はself, 1番目は_cmd | |
[invocation setArgument:&arg2Buff atIndex:2]; | |
[invocation invoke]; | |
[invocation getReturnValue:&result]; | |
} | |
NSLog(@"result=>%d", result); | |
} | |
@end | |
int main(int argc, char *argv[]) | |
{ | |
@autoreleasepool { | |
id obj = [[TestObj alloc] init]; | |
[obj run]; | |
[obj release]; | |
//Xcodeで実行する時はこの辺にbreak point張るといいと思います | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment