gpt4 book ai didi

iphone - 为 UITableView 存储来自网络的图像

转载 作者:行者123 更新时间:2023-11-28 18:13:23 25 4
gpt4 key购买 nike

我有一个带有显示文本和图像的自定义单元格的 UITableView。(右侧图像)。起初,一切正常,但后来我注意到滚动时,整个 tableview 都滞后了。这是因为该应用程序可能在重新使用它们时在单元格进入屏幕时下载了单元格图像。我添加了一个 NSCache 来存储下载的图像,并告诉 cellForRowAtIndexPath 加载 imageName 如果它存在,否则,再次从互联网下载。然而,缓存是短期存储,如果我用主页按钮退出我的应用程序,然后重新进入,那么只剩下一些图像,必须重新下载图像。

我正在尝试找出比缓存更长期存储图像的最佳方法。我已经阅读了一些关于 NSDirectory 和存储在应用程序库中的内容,但还没有弄清楚..

我认为,最合乎逻辑的解决方案是做这样的事情:

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

/*stuff*/

NSString *imageName = [dictionary objectForKey:@"Image"];
UIImage *image = [--Cache-directory-- objectForKey:imageName]; //Try to get it from cache

if(image) //If image was received from cache:
{
cell.imageView.Image = image;
}
else //If not in cache:
{
image = [--local-directory-- objectForKey:imageName]; //Check some local directory

if(image) //If image received from directory:
{
cell.imageView.Image = image;
// + Also save it to the cache?
}
else //If image was in neither cache or local directory, get it from the website with given URL
{
image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:imageURL]];
//Then save to cache and to file?
}
}


}

图像很少更改或关闭,但并不罕见到我愿意事先在应用程序中实现它们,因此每次添加图像时我都必须发布更新。

这在我看来是合乎逻辑的。我在正确的轨道上吗?我如何“调用”本地目录?就像,如果我将图像添加到 NSDirectory 对象或其他东西,这不会每次都被重置吗?如何访问本地文件夹?

最佳答案

你从错误的方向攻击问题...
问题是 tableView 滞后。
原因是因为你在主线程中下载你的图像。
即使您将从光盘中读取图像,您仍然无法获得最佳的滚动性能。

所以一定不要阻塞你的主线程。为此,您可以异步下载图片,或使用 GCD 在另一个线程中下载。

像这样:

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

/*stuff*/

// this will block your main thread, bad idea..
//image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:imageURL]];

// instead call it in a separate thread
dispatch_queue_t imgDownloaderQueue = dispatch_queue_create("imageDownloader", NULL);
dispatch_async(imgDownloaderQueue, ^{
// download the image in separate thread
UIImage *image = [[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:imageURL]] autorelease];
dispatch_queue_t main_queue = dispatch_get_main_queue();
dispatch_sync(main_queue, ^{
// this is called in the main thread after the download has finished, here u update the cell's imageView with the new image
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.imageView.image = image;
});
});
dispatch_release(imgDownloaderQueue);
}

关于iphone - 为 UITableView 存储来自网络的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11530284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com