C4 - 尝试通过NSString调用方法时捕获异常

时间:2014-05-19 15:15:13

标签: c4

我正在尝试制作演示应用,并且我已经构建了一些将对象放到画布上的方法。我想要做的是使用字符串连接来调用方法(每个方法以其幻灯片索引命名)。当我使用runMethod调用方法时,如果我调用一个不存在的方法,它将崩溃。我尝试将其包装在try / catch / final结构中,但应用程序仍然崩溃。

NSString * slidename = [NSString stringWithFormat:@"showSlide%d", counter];

@try {
    [self runMethod:slidename afterDelay:0];
}
@catch (NSException *exception) {
    NSLog(@"Exception: %@", exception);
}
@finally {
}

1 个答案:

答案 0 :(得分:1)

你很亲密。缺少的是能够在尝试运行之前检查方法是否存在,然后捕获任何异常。

C4的runMethodNSObject performSelector的包装器,它通过要求字符串作为方法的名称而不是传递选择器来隐藏处理选择器。在您的情况下,您真的想要寻找选择器来确定您是否可以运行该方法。

以下作品:

-(void)setup {
    NSArray *methodNames = @[@"aMethod",@"method2",@"anotherMethod"];
    for(int i = 0; i < methodNames.count; i++) {
        NSString *currentMethod = methodNames[i];
        if ([self respondsToSelector:NSSelectorFromString(currentMethod)]) {
            [self runMethod:currentMethod afterDelay:0];
        } else {
            C4Log(@"does not respond to %@",currentMethod);
        }
    }
}

-(void)aMethod{
    C4Log(NSStringFromSelector(_cmd));
}

-(void)anotherMethod{
    C4Log(NSStringFromSelector(_cmd));
}

这个输出是:

[C4Log] does not respond to method2
[C4Log] aMethod
[C4Log] anotherMethod

在你的情况下可能发生的事情是try-catch实际上没有传递异常因为 runMethod实际上正在执行就好了。延迟使得方法的执行你正在运行下一个运行循环,那就是实际失败的时候。

您也可以尝试:

NSString * slidename = [NSString stringWithFormat:@"showSlide%d", counter];

@try {
    [self performSelector:NSSelectorFromString:(slidename)];
}
@catch (NSException *exception) {
    NSLog(@"Exception: %@", exception);
}
@finally {
}

应立即执行该方法。

相关问题