使用nsinvocation来调用警报方法

时间:2012-09-05 14:37:03

标签: objective-c ios cocoa

我试图从myMethod调用showUIAlertView但得到一个例外:由于未被捕获而终止应用程序 异常'NSInvalidArgumentException',原因:'+ [NSInvocation invocationWithMethodSignature:]:方法签名参数不能为nil' 另外,请在行“[invocation setTarget:self];”中告诉我要写什么作为setTarget的参数,我写了自己,因为这两个方法都在同一个文件中。 谢谢!

- (void)showUIAlertView:(NSString*)title:(NSString*)message
{
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title
                                                      message:message
                                                      delegate:nil 
                                               cancelButtonTitle:@"OK"
                                               otherButtonTitles:nil];
    [alertView show];
}

- (void)myMethod:(NSString*)someData
{
    //some lines of code
    SEL selector = @selector(showUIAlertView:title:);
    NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    [invocation setSelector:selector];
     NSString *str1 = @"Status Message";
     NSString *str2 = @"You are not a member yet.";
     [invocation setTarget:self];
     [invocation setArgument:&str1 atIndex:2];
     [invocation setArgument:&str2 atIndex:3];
    [NSTimer scheduledTimerWithTimeInterval:0.1 invocation:invocation repeats:NO];

}

1 个答案:

答案 0 :(得分:0)

根据错误消息跟踪问题:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSInvocation invocationWithMethodSignature:]: method signature argument cannot be nil'

这意味着[[self class] instanceMethodSignatureForSelector:selector];nil选择器返回了showUIAlertView:title:。为什么?因为你的类只是没有实现与选择器相对应的消息 - 你在方法声明中混淆了标签和参数名称:

- (void)showUIAlertView:(NSString*)title:(NSString*)message;

实际上应该是

- (void)showUIAlertView:(NSString*)title title:(NSString*)message;

此外,将目标设置为self很好 - target是您要调用选择器/调用的对象。