繁体   English   中英

使用GCD在UITableView中异步加载图像

[英]Easy load images asynchronously in a UITableView using GCD

经过两天的搜索,我找到了解决方案。

  • 使用GCD异步下载图像。
  • 使用NSMutableDictionary在内存中保存图像。

我找到了Duncan C在这里解释的解决方案:

http://iphonedevsdk.com/forum/iphone-sdk-development/104438-grand-central-dispatch-tableview-images-from-the-web.html

如何实施:

- (void)viewDidLoad
{
(...)
dispatch_queue_t mainQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

imagesDictionary = [[NSMutableDictionary alloc] init];
  (...)
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
(...)

NSData *imageData = [imagesDictionary objectForKey:@"IMAGE URL"];

    if (imageData)
    {
        UIImage* image = [[UIImage alloc] initWithData:imageData];

        imageFlag.image = image;
        NSLog(@" Reatriving ImageData...: %@", @"IMAGE URL");


    }
    else
    {

    dispatch_async(mainQueue, ^(void) {

        NSString *url = @"IMAGE URL";
        NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
        UIImage* image = [[UIImage alloc] initWithData:imageData];

        imageFlag.image = image;

        [imagesDictionary setObject:imageData forKey:@"IMAGE URL"];

        NSLog(@" Downloading Image...: %@", @"IMAGE URL");

    });

    }

(...)
}

GitHub中的项目: https//github.com/GabrielMassana/AsynchronousV2.git

我知道如果项目很大并且有很多单元格,我可能会耗尽内存。 但我认为这个解决方案对于新手来说是个不错的方法。

你对这个项目有什么看法? 如果项目非常大,最好的选择是将图像保存在磁盘中吗? 但问题是磁盘内存耗尽的可能性,不是吗? 也许,那么,我们需要一种机制来删除磁盘上的所有图像。

使用NSCache保存下载的图像而不是NSDictionary。 这将在低内存情况下管理自己并删除暂时未访问的项目。 在这种情况下,如果需要,将再次从URL加载它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM