Try-Catch错误目标C.

Pra*_*rad 3 error-handling objective-c try-catch-finally ios

我试图从给定的Instagram图片中获取字幕,但是如果没有标题,应用程序会抛出异常并崩溃.我将如何实现@try@catch执行此操作.这是我到目前为止:

@try {
    RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:[NSString stringWithFormat:@"%@",entry[@"user"][@"full_name"]] message:[NSString stringWithFormat:@"%@",text[@"caption"][@"text"]]];
    [modal show];
}
@catch (NSException *exception) {
    NSLog(@"Exception:%@",exception);
}
@finally {
  //Display Alternative
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 6

这不是一个很好的使用异常和try- catch- finally块.如果标题是,你说你得到了例外nil.那么,为了优雅地处理这种情况,您希望您的应用程序究竟做什么?根本不显示对话框?然后你可能会这样做:

NSString *user = entry[@"user"][@"full_name"];
NSString *caption = text[@"caption"][@"text"];

if (caption != nil && caption != [NSNull null] && user != nil && user != [NSNull null]) {
    RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:user message:caption];
    [modal show];
}
Run Code Online (Sandbox Code Playgroud)

或者,如果有nil以下情况,您可能希望展示其他内容:

NSString *user = entry[@"user"][@"full_name"];
NSString *caption = text[@"caption"][@"text"];

if (caption == nil || caption == [NSNull null])
    caption = @"";     // or you might have @"(no caption)" ... whatever you want
if (user == nil || user == [NSNull null])
    user = @"";

RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:user message:caption];
[modal show];
Run Code Online (Sandbox Code Playgroud)

或者,如果您有源代码RNBlurModalView,也许您可​​以诊断为什么在标题出现时正确生成异常nil,并在那里修复该问题.

有很多可能的方法,取决于您希望应用程序在这些情况下做什么,但异常处理无疑是正确的方法.作为使用Objective-C编程指南的" 处理错误"部分,异常是针对意外的"程序员错误",而不是简单的逻辑错误,并且正如他们所说:

您不应该使用try-catch块代替Objective-C方法的标准编程检查.