[英]UITableView with image in cell stucks
我正在开发一个使用UITableView的应用程序,该应用程序包含具有大小为320 X 200的UIImageView的单元格。此图像来自Web URL,并存储到我的应用程序文件夹中。然后向用户显示此图像。
为此,我正在使用“ UIImageView + AFNetworking.h”类的以下方法。
- (void)setImageWithURL:(NSString *)url
placeholderImageName:(NSString *)placeholderImage
saveFilePath:(NSString *) filePath
IndexPath:(NSIndexPath *)indexPath
success:(void (^)(NSIndexPath *indexPath, UIImage *image))success
failure:(void (^)(NSIndexPath *indexPath, NSError *error))failure {
NSLog(@"DOWNLOAD IMG URL :: %@", url);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[request setHTTPShouldHandleCookies:NO];
[request setHTTPShouldUsePipelining:YES];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
[self setImageWithURLRequest:request
placeholderImage:placeholderImage == nil? nil : [UIImage imageNamed:placeholderImage]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
[Storage SaveImage:image WithFileName:filePath];
if (success)
success(indexPath, image);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
if (failure)
failure(indexPath, error);
}
];
}
当我的所有图像下载到我的本地文件夹之后,该表格视图在显示图像时卡住了。
下载有可能与主线程同步进行,并阻止它直到下载完成。
为此 ,我在项目中使用了SDWebImage 。 它的工作真的非常好。
编辑:
好的,AFNetworking正在异步完成所有工作,并且还缓存了所有图像。 请参阅文档 。
如果您不需要成功和失败的障碍,则可以不使用它。
- (void)setImageWithURL:(NSString *)url
placeholderImageName:(NSString *)placeholderImage {
NSURL *url = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
UIImage *pImage = placeholderImage == nil? nil : [UIImage imageNamed:placeholderImage];
[self setImageWithURL:url placeholderImage:pImage];
}
或者,图像可能非常大(与UIImageView大小无关)。 我们可以看到您的代码吗? 您是否从文件系统手动加载它们? 可能是因为您在主线程中执行了该操作。 在加载图像的代码中尝试以下操作:NSLog(@“这是主线程:%d”,[NSThread isMainThread]); 如果看到1,那就是问题所在。 您可以使用GCD解决此问题(请记住,一旦加载图片,请将其移至主线程)
使用NSOperationQueue下载图像。 在NSOperationQueue中添加新项目时,首先检查它是否已添加。
NSOperation完成后,该映像将保存到本地。
始终从本地加载图像。 如果本地没有图像,则显示一些占位符。
希望能帮助到你。
此致Punita
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.