Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.
- (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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした