【问题标题】:IOS- Use to Try/Catch for load JsonIOS-用于尝试/捕获加载Json
【发布时间】:2012-10-20 03:18:27
【问题描述】:

我正在从服务器加载数据,但有时服务器未连接(错误)。

我想用 Try/Catch 之类的东西来避免错误应用

1:在加载数据时尝试/cactch 2:尝试/捕捉图像

不知道怎么用 我写的代码是:

@try
{
 dispatch_async(htvque, ^{
        NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString:listChannel]];
        NSError* error;
        jsonTable = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        if (error) {
            NSLog(@"%@", error);
        }
        else
        {
             NSMutableArray *arrImage = [jsonTable objectForKey:@"ListImage"];
        for (int i =0; i<arrImage.count; i++) {
            UIImage * result;
            UIImageView *imgView = [[UIImageView alloc] init];
            imgView.frame  = CGRectMake(0, 30 * i , 20, 20);
            imgView.image = result;
            @try
            { 
               NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:                               [arrImage objectAtIndex:i]]];
               result = [UIImage imageWithData:data];
               [self.view addSubview:imgView];
            }
            @catch
            {}
            @finally
            {}


        }

        }
    });
}
@catch(NSException * exp)
{
  NSLOG(@"abc");
}
@finnaly
{

}

【问题讨论】:

  • 您不应该在后台线程上编辑界面。另外,贴出exp的内容。
  • 服务器死机时的错误,try/catch不使用,应用程序错误

标签: objective-c ios exception-handling error-handling try-catch


【解决方案1】:

不要为此目的为您的 ObjC 程序使用异常。

在 ObjC 中,仅在以下情况下保留使用异常:

  • 您不打算恢复
  • 当您不打算恢复时

-- if 一个例外在那里甚至是合适的(我只是不使用它们,但这对很多人来说有点太“核心”了)。

无论如何 - ObjC 中的异常表示程序员错误,并且在逻辑上是您无法期望从中恢复的(与其他语言不同)。找出你的错误是什么,而不是“尝试并吞下”错误处理。

我建议的补救措施是创建一个新问题,显示相应的代码,并详细说明异常、如何重现它等。


注意:实际上,有一些古怪的 Cocoa API 会抛出较少的异常情况,而它们本应使用另一种错误处理方法,例如 NSError。您将在开发中看到的绝大多数 Cocoa 异常都是您应该并且可以纠正的问题(范围错误、不响应选择器、引用计数)。

【讨论】:

  • 更重要的是,默认情况下,异常在 ARC 下是不安全的。如果您在 ARC 下捕获异常,您将泄漏对象(默认情况下。您可以打开一个使其安全的选项。)
  • @mattjgalloway 实际上,您的示例只是几种潜在副作用中的一种 (+1)。 MRC 具有类似的泄漏和破坏复杂性。其他示例是 a) 跨模块边界抛出并不可靠和 b) 并且存在拦截异常的实现。
  • 对不起,你能给我样品吗,我不知道如何
【解决方案2】:

我认为这将是一种相当稳健的方式来做你想做的事。我希望该示例在不依赖 try/catch 的情况下显示很多错误检查

dispatch_async(htvque, ^{
    NSError* error = nil;
    NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:listChannel] options:0 error:&error];
    if (error) { NSLog(@"%@", error); return; }

    NSDictionary *jsonTable = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    if (error) { NSLog(@"%@", error); return; }
    if (![jsonTable isKindOfClass:[NSDictionary class]]) { NSLog(@"jsonTable is not an NSDictionary: %@", jsonTable); return; }

    NSArray *images = [jsonTable objectForKey:@"ListImage"];
    if (![images isKindOfClass:[NSArray class]]) { NSLog(@"images is not an NSArray: %@", images); return; }

    NSMutableArray *dataForImages = [NSMutableArray arrayWithCapacity:images.count];

    // Build up an array with all the image data. For simplicity sake, I'll just skip ones the fail to load.
    for (NSString *URLString in images) {
        if (![URLString isKindOfClass:[NSString class]]) { NSLog(@"URLString is not an NSString: %@", URLString); continue; }

        NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:URLString] options:0 error:&error];
        if (error) { NSLog(@"%@", error); continue; }

        [dataForImages addObject:data];
    }

    // MUST SWITCH TO MAIN QUEUE BEFORE UPDATING UI!!!!!!!
    dispatch_sync(dispatch_get_main_queue(), ^{
        // This is just a different way of iterating the array.
        [dataForImages enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            UIImage *image = [UIImage imageWithData:obj];
            if (!image) { NSLog(@"Could not create image from data at index %d", idx); return; }

            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
            imageView.frame = CGRectMake(0, 30 * idx , 20, 20);

            [self.view addSubview:imageView];
        }];
    });
});

这真的不应该是一个可行的解决方案,而是一个粗略的大纲。

【讨论】:

  • 不幸的是,当json不从服务器加载数据时,应用程序仍然崩溃(服务器死亡)!
  • @heaven 什么是崩溃?你可以在调试器窗口中发布实际输出吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 2019-09-10
  • 1970-01-01
  • 2019-08-25
  • 2017-09-12
  • 1970-01-01
相关资源
最近更新 更多