【问题标题】:How to correctly catch exceptions while view is loading加载视图时如何正确捕获异常
【发布时间】:2016-05-28 10:09:19
【问题描述】:

我想了解如何正确捕获并向用户显示在处理 viewDidLoad 时出现的异常原因?我试图像这样解决这个问题,但我在显示 AlertWindow 时遇到了问题。 错误:由于未捕获的异常,无法识别的选择器发送到实例并终止应用程序。

- (void)viewDidLoad {
    @try {
        [super viewDidLoad];
        APPDataBase *sharedDataBase = [APPDataBase sharedDataBase];
        self.navigationItem.hidesBackButton = YES;
        recievedArray = [recievedURL componentsSeparatedByString:@" "];
        [self fillUpTableViewWithTitles];
        if ([self isInternetConnected]){
            [sharedDataBase saveData:feeds WithKey:@"savedFeeds"];
        }
        else
        {
            feeds = [sharedDataBase loadDataWithKey:@"savedFeeds"];
        }
        [NSException raise:@"Invalid smth" format:@"Error error error, dangerous, wow"];
    }
    @catch (NSException *exception) {
        [self showAlertWindowWithString:exception];
    }
}

和showAlertWindowWithString:方法代码

-(void)showAlertWindowWithString:(NSString *)string{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:string message:@"Press OK button." preferredStyle:UIAlertControllerStyleAlert];
    alertController.view.frame = [[UIScreen mainScreen] applicationFrame];

    [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        [self okButtonTapped];
    }]];

    UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (topRootViewController.presentedViewController){
        topRootViewController = topRootViewController.presentedViewController;
    }

    [topRootViewController presentViewController:alertController animated:YES completion:nil];
}

我有点搞砸了,因为我只能访问 iDevice Emulator,所以我想至少使用这种方式来捕捉“现实生活中的设备”错误。或者,也许有其他方法可以让应用在发生此类异常时不崩溃?

【问题讨论】:

    标签: ios exception try-catch


    【解决方案1】:

    您将NSException * 传递给showAlertWindowWithString: 方法,但将其作为NSString * 接收,但string 仍然是NSException - 然后将其传递给alertControllerWithTitle - 只要该方法尝试对NSException 执行NSString 操作,您将得到一个无法识别的选择器异常。

    你可以这样做:

    @catch (NSException *exception) {
        [self showAlertWindowWithString:exception.reason];
    }
    

    但实际上,@try/@catch 在 Objective C iOS 编程中并不是一个常见的范例。更常见的是简单地检查错误并采取适当的措施或显示用户友好的警报和消息。通常应在开发过程中识别异常,并修复异常的根本原因。

    【讨论】:

    • 感谢您的帮助,我将尝试检查代码中所有可能的问题片段并“采取适当的措施或显示用户友好的警报和消息”´=)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 2012-11-08
    • 2018-07-28
    • 1970-01-01
    • 2010-11-07
    相关资源
    最近更新 更多