Ios 如何在加载视图时正确捕获异常

Ios 如何在加载视图时正确捕获异常,ios,exception,try-catch,Ios,Exception,Try Catch,我想了解如何正确捕获并向用户显示处理viewDidLoad时出现的异常原因?我曾试图像这样解决这个问题,但我遇到了显示AlertWindow的问题。 错误:由于未捕获异常,无法识别的选择器已发送到实例并终止应用程序 - (void)viewDidLoad { @try { [super viewDidLoad]; APPDataBase *sharedDataBase = [APPDataBase sharedDataBase]; self

我想了解如何正确捕获并向用户显示处理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,所以我想至少用这种方式捕捉“真实设备”错误。或者,可能还有其他方法可以使应用程序在发生此类异常时不会崩溃?

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

你可以这样做:

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

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

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

你可以这样做:

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

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

谢谢您的帮助,我将尝试检查代码中所有可能的问题片段并“采取适当的操作或显示用户友好的警报和消息”')=)谢谢您的帮助,我将尝试检查代码中所有可能的问题片段,并“采取适当的操作或显示用户友好的警报和消息”')=)