I am trying to get Captions from a given instagram picture, however if there is no caption the app throws an exception and crashes. How would I implement @try and @catch to do this. Here is what i have so far:

@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
}
有帮助吗?

解决方案

This is not a good use of exceptions and try-catch-finally blocks. You say that you get the exception if the caption is nil. So, what precisely do you want your app to do in order to gracefully handle this situation? Not show the dialog at all? Then you might do something like:

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];
}

Or perhaps you want to show something else if those are 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];

Or, if you have the source code for RNBlurModalView, perhaps you can diagnose why precisely it's generating an exception when the caption is nil, and fix that issue there.

There are lots of possible approaches, dependent upon precisely what you want the app to do in these situation, but exception handling is undoubtedly not the right approach. As the Dealing With Errors section of the Programming with Objective-C guide, exceptions are intended for unanticipated "programmer errors", not simple logic errors, and as they say:

You should not use a try-catch block in place of standard programming checks for Objective-C methods.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top