簡體   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