UIAlertView delegate method crashing

2019-07-17 19:35发布

In my iPhone app, I have a NSObjectA class and a UIViewController B class. I want to call a instance method in B class from A. I used the following code.

Bclass *vc = [[Bclass alloc]init];
[vc hideAlert:NSString];
[vc release];

and in B class:

- (void)hideAlert:(NSString*)message{
    UIAlertView *shareAlrt = [[UIAlertView alloc] initWithTitle:@""
                                                        message:message
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil];
    [shareAlrt show];
    [shareAlrt release];
}

and the method called and show a AlertView. When click on the Ok button, I want to navigate to class Cclass.

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        Cclass *vc = [[Cclass alloc]initWithNibName:@"Cclass" bundle:[NSBundle mainBundle]];
        [self presentModalViewController:vc animated:NO];
        [vc release];
    }
}

But when I click on the Ok button, the app crashes. Whats happening here? I have added <UIAlertViewDelegate> in the B class.h file, but still the same error. Please help

I am getting the error code *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType alertView:clickedButtonAtIndex:]: unrecognized selector sent to instance 0x81baa80'

2条回答
在下西门庆
2楼-- · 2019-07-17 20:00

This has been answered by presuming that u have no other button except cancel button titled as "OK". Assumption is made by seeing your displayed code.

You have used Cancel button on which u cant handle delegate to perform any action.

If you look at the documentation of UIAlertViewDelegate class reference

Optionally, you can implement the alertViewCancel: method to take the appropriate action when the system cancels your alert view. If the delegate does not implement this method, the default behavior is to simulate the user clicking the cancel button and closing the view.

查看更多
冷血范
3楼-- · 2019-07-17 20:03

Just change the method

- (void)hideAlert:(NSString*)message{
    UIAlertView *shareAlrt = [[UIAlertView alloc] initWithTitle:@""
                                                    message:message
                                                   delegate:self
                                          cancelButtonTitle:nil
                                          otherButtonTitles:@"Ok",nil];
    [shareAlrt show];
    [shareAlrt release];
}
查看更多
登录 后发表回答