5

假设我们有不同的对象,它们具有相同的方法名称但具有不同的参数类型,例如:getMethod:(NSNumber*)aNumbergetMethod:(NSString*)aString

如何使用 respondsToSelector 或通过其他方式检查对象是否响应具有特定参数类型的选择器,如下所示:

[myObjectA respondsToSelector:@selector(getMethod:(NSNumber*))]

你怎么做到这一点?谢谢。

4

2 回答 2

4

You have a couple of ways to find type names of arguments for selector. For example this code will work:

Method method = class_getInstanceMethod([self class], @selector(someMethod:param2:param3:));
char type[256];
int argsNumber = method_getNumberOfArguments(method);
for (int i = 0; i < argsNumber; i++) {
    method_getArgumentType(method, i, type, 256);
    NSLog(@"%s", type);
}

First and second log arguments are system and you are not interested in them, so another tree lines are that you need.

also code below will give you same result

NSMethodSignature *sig = [self methodSignatureForSelector:@selector(someMethod:param2:param3:)];
int args = [sig numberOfArguments];
for (int i = 0; i < args; i++) {
    NSLog(@"%s", [sig getArgumentTypeAtIndex:i]);
}

someMethod:param2:param3: can have implementation like this for example

- (BOOL) someMethod:(NSString *)str param2:(UIView *)view param3:(NSInteger)number
{
    return NO;
}

BUT! Of cause we have big but here )) In both cases you will have arguments types names with const char * string with length a one symbol. Compiler encodes types name as described here. You can differ int from char but not UIView from NSString. For all id types you will have type name '@' that means it's id. Sad but true. Unfortunately I've not found any ways to get whole complete type name or decode given. If you will find this way let me know pls.

So this is solution. Hope you will find the way how to use this approach in your project.

于 2013-02-12T12:36:27.187 回答
1

您实际上无法区分方法参数类型,但也许您可以执行以下操作:

if([myObject isKindOfClass:[A class]])
     [myObjectA getMethod:aNumber];
else if([myObject isKindOfClass:[B class]])
     [myObjectA getMethod:aString];

您无需检查它是否响应选择器,因为您已检查其类型是否正确。也许您的问题比这更复杂,但如果不是,这应该可以工作。

于 2013-02-12T10:52:12.197 回答