LoginSignup
19

More than 5 years have passed since last update.

NSInvocation を使ってクラスメソッドを呼ぶ

Posted at

少しハマったのでメモ的に。

[NSObject performSelector:withObject:withObject];
は動的にメソッドを呼ぶ時に便利ですが、パラメータが3つ以上ある場合には使えません。その場合は NSInvocation を使うことで複雑な動的呼び出しができます。

で、クラスメッソドを呼ぶ場合はどうしたら良いのかなーと思ったのですが、

  • setTarget に Class を渡す
  • method signature の取得に、instanceMethodSignatureForSelector ではなく methodSignatureForSelector を使う
// define selector
SEL selector = @selector(postToURL:withParams:async:);
// get method signeture
NSMethodSignature* signature = [[self class] methodSignatureForSelector: selector];
// make NSInvocation instance
NSInvocation* invocation = [ NSInvocation invocationWithMethodSignature: signature ];
[invocation setSelector:selector];
[invocation setTarget:[self class]];
[invocation setArgument:&strurl atIndex:2];
[invocation setArgument:&params atIndex:3];
[invocation setArgument:&completionBlock atIndex:4];
[invocation invoke];

最初、setSelector をしていなくてエラーになってしまいハマりました・・・

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19