Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What are the problem?

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
2
Help us understand the problem. What are the problem?