3

特定の 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
}
4

1 に答える 1

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

または、次の場合は何か他のものを表示したいかもしれません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];

または、 のソース コードがあるRNBlurModalView場合は、キャプションが のときに例外が生成される理由を正確に診断し、nilそこでその問題を修正できます。

このような状況でアプリに何をさせたいかによって、さまざまなアプローチが考えられますが、例外処理は間違いなく適切なアプローチではありません。Objective-C を使用したプログラミングガイドの「エラーの処理」セクションのように、例外は単純な論理エラーではなく、予期しない「プログラマ エラー」を対象としています。

Objective-C メソッドの標準プログラミング チェックの代わりに try-catch ブロックを使用しないでください。

于 2013-08-07T01:58:51.037 に答える