Objective C >> Is there a way to check a Selector return value?

只愿长相守 提交于 2019-11-30 16:16:03

问题


let's say I have a selector that may be assigned to several different methods - each one has a different return value.

Is there a way to check what is the return value of the method the selector is holding before calling "performSelector"?


回答1:


Is there a way to check what is the return value of the method the selector is holding before calling "performSelector"?

Value? No. Type? Yap. It seems that you want the return type of the method (or your question wouldn't make sense).

Method m = class_getInstanceMethod([SomeClass class], @selector(foo:bar:));
char type[128];
method_getReturnType(m, type, sizeof(type));

Then you can examine the returned type string in type. For example, "v" means void (google the full list).




回答2:


you might use NSInvocation which is recommended in Apple Docs for this purpose

here is some sample code for using NSInvocation

    SEL selector = NSSelectorFromString(@"someSelector");
if ([someInstance respondsToSelector:selector]) {
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
                                [[someInstance class] instanceMethodSignatureForSelector:selector]];
    [invocation setSelector:selector];
    [invocation setTarget:someInstance];
    [invocation invoke];
    float returnValue;
    [invocation getReturnValue:&returnValue];
    NSLog(@"Returned %f", returnValue);
}



回答3:


If the method doesn’t return an object (it returns a primitive type), then use NSInvocation instead.

@implementation NSObject(SafePerformSelector)
-(id) performSelectorSafely:(SEL)aSelector;
{
    NSParameterAssert(aSelector != NULL);
    NSParameterAssert([self respondsToSelector:aSelector]);

    NSMethodSignature* methodSig = [self methodSignatureForSelector:aSelector];
    if(methodSig == nil)
        return nil;

    const char* retType = [methodSig methodReturnType];
    if(strcmp(retType, @encode(id)) == 0 || strcmp(retType, @encode(void)) == 0){
        return [self performSelector:aSelector];
    } else {
        NSLog(@"-[%@ performSelector:@selector(%@)] shouldn't be used. The selector doesn't return an object or void", [self class], NSStringFromSelector(aSelector));
        return nil;
    }
}
@end



回答4:


performSelector: always returns an id. The actual type returned is determined by the method you call; so there is no way to know it beforehand.



来源:https://stackoverflow.com/questions/14602854/objective-c-is-there-a-way-to-check-a-selector-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!