簡體   English   中英

在Dispatch_queue的UITableView單元格中獲取相同的圖像

[英]Getting same images in UITableView cell in Dispatch_queue

我正在從服務器添加圖像。 我正在使用NSMutableArray和自定義UITableViewCell。 問題:運行項目時。 UITableViewCell顯示相同的圖像。 我認為它令人耳目一新。 我該如何解決該問題?

下面是我使用的調度方法

   dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        //this will start the image loading in bg
        dispatch_async(concurrentQueue, ^{
            NSError *nserror = nil;
            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString: [imagesArray2 objectAtIndex:indexPath.row]]options:NSDataReadingUncached error:&nserror];

            //this will set the image when loading is finished
            dispatch_async(dispatch_get_main_queue(), ^{
                if (nserror)
                {
                    [cell.imgview setImage:[UIImage imageNamed:@"placeholderimage.png"]];
                }
                else
                {
                    [cell.imgview setImage:[UIImage imageWithData:imageData]];
                }
                [mytablview reloadData];
            });
        });

謝謝你的幫助。

這並不能真正回答您的問題,但可以幫助您改變前進的方向。

完成加載圖像后,單元格可能已經開始加載其他圖像,因為UITableView重復使用了它們的單元格。 異步加載圖像並在完成后對其進行設置的操作不會被取消,因此您將在整個商店中彈出不正確的圖像,因為無法保證首先完成哪個圖像加載。

請參閱我對AFNetworking的評論,我強烈建議您使用它,但是如果您走的路不對 ,則應該使用某種NSOperation子類來加載圖像。 這樣,您可以在重用單元格時取消操作,然后可以安全地為該單元格加載其他圖像。

在加載新圖像之前,只需重置單元格imageView即可。

   [cell.imgview setImage:[UIImage imageNamed:@"placeholderimage.png"]];
   dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(concurrentQueue, ^{
            NSError *nserror = nil;
            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString: [imagesArray2 objectAtIndex:indexPath.row]]options:NSDataReadingUncached error:&nserror];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (nserror) {
                    [cell.imgview setImage:[UIImage imageNamed:@"placeholderimage.png"]];
                } else {
                    [cell.imgview setImage:[UIImage imageWithData:imageData]];
                }
            });
        });

將網址保存在最終顯示圖片的單元格中。 然后,當您嘗試在到達圖像后顯示圖像時,請確保該單元格中的網址與您要顯示的圖像的網址匹配。 如果不匹配,則不顯示; 這意味着該單元已被重用(由於滾動或刷新),並且不再需要該圖像。 無需停止圖像加載,只需停止顯示即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM