iOS 具有 JSON 个对象的表视图

iOS tableview with JSON objects

在我的 iOS 应用程序中,我显示了一个表格视图,其中包含从 URL 下载的 JSON 个对象。现在,tableview 滚动非常慢,当显示最后一行时,图像有时会超出图像视图容器,看起来完全混乱。这是处理单元格内图像视图的 cellForRowAtIndexPath 方法中的代码:

       NSMutableString *logo = [[NSMutableString alloc]initWithString:@"http://not shown here"];

       NSString *imageURL = [[categorias objectAtIndex:indexPath.row] objectForKey:@"imagen"];
        NSLog(@"URL = %@",imageURL);


        if(imageURL != nil && ![imageURL isEqual:[NSNull null]])
        {
            [logo appendString:imageURL];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                NSURL *logoURL = [NSURL URLWithString:logo];
                NSData *logoData = [NSData dataWithContentsOfURL:logoURL];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (logoData.length) {
                        cell.imagen_label.image = [UIImage imageWithData:logoData];
                    }else{
                        cell.imagen_label.image = [UIImage imageNamed:@"no_image.png"];
                    }
                });
            });
        }

我需要你的帮助来改进 tableview 的行为。

一个问题是,当用户向下滚动时,代码将为每个单元格分配一个 dataWithContentsOfURL。如果用户滚动得非常快,那将导致大量下载排队,即使是那些已经滚动到屏幕外的下载。

此外,通过这种双重调度,内部调度块将保留单元格,直到下载图像并执行内部调度。 table 可能已经将单元格重新用于其他图像。如果发生这种情况,可能会显示错误的图像。它将以最后完成的为准。 (当滚动停止时,您可能会看到它多次更改。

WWDC 2011 第 211 节的视频中有很好的示例说明如何执行此操作 "Building Concurrent User Interfaces on iOS"