LoginSignup
2
2

More than 5 years have passed since last update.

セレクタからメソッドシグネチャの引数の数を調べる

Last updated at Posted at 2014-02-21

- (NSUInteger)argc:(SEL)sel
{
    return [[NSStringFromSelector(sel) componentsSeparatedByString:@":"] count];
}

原始的ですが。

※2014/02/22 @tomohisaota さんから教えていただきました。
recieverが分かっている場合はNSMethodSignatureを使うほうが良さそうです。


- (NSUInteger)argc:(SEL)sel
{
    NSLog(@"%d",[self methodSignatureForSelector:@selector(viewDidAppear:)].numberOfArguments); // => 2 + 1 = 3
}

※ 2014/02/22 追加

NSObjectのmethodSignatureForSelector:の挙動について

調べたいセレクタがプロトコルの場合、レシーバがプロトコルを採用している場合は返してくれるようですが、明示的に採用していないオブジェクトは返してくれないみたいです。


#import <XCTest/XCTest.h>

@protocol HogeProtocol

@optional
- (void)hoge:(int)hoge fuga:(int)fuga var:(int)var;

@end

@interface ObjcTests : XCTestCase <HogeProtocol>

@end

@implementation ObjcTests

- (void)testArgc
{
    NSUInteger i;
    XCTAssertNoThrow(i = [[self methodSignatureForSelector:@selector(hoge:fuga:var:)] numberOfArguments], );
    XCTAssert(i == 5,); // 2 + 3 = 5
    NSObject *ob = [NSObject new];
    XCTAssertNoThrow(i = [[ob methodSignatureForSelector:@selector(hoge:fuga:var:)] numberOfArguments], );
    XCTAssertFalse(i == 5, ); // 0
}

@end

2
2
2

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
2
2