Objective-C 中 AQGridView 延迟加载图像
在我的应用程序中,我有一个根视图,它是一个网格视图。我正在 gridview 单元格中加载图像。我在加载图像时遇到问题。一旦我启动应用程序,图像加载到单元格中一秒钟后,就会出现没有图像的空白单元格。有什么办法可以解决这个问题吗?下面是我的代码。
UIImage *defaultImage = [UIImage imageNamed:@"addEmployee.png"];
if (!employee.imageName) {
return defaultImage;
}
if ([_imageCache objectForKey:employee.imageName]) {
return [_imageCache objectForKey:employee.imageName];
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
UIImage *image = [UIImage imageWithContentsOfFile:[self imagePath:employee.imageName]];
dispatch_async(dispatch_get_main_queue(), ^ {
if (image) {
[_imageCache setObject:image forKey:employee.imageName];
cell.imageView.image = image;
} else {
[_imageCache setObject:defaultImage forKey:employee.imageName];
cell.imageView.image = defaultImage;
return;
}
});
});
return cell.imageView.image;
}
In my app, I have a root view which is a gridview. I am loading an images in the gridview cells.I am having problem with the loading images. As soon as I launch the app, there will be blank cells with out images after a second the images are loading into the cells. Is there any way to solve this issue. The below is my code.
UIImage *defaultImage = [UIImage imageNamed:@"addEmployee.png"];
if (!employee.imageName) {
return defaultImage;
}
if ([_imageCache objectForKey:employee.imageName]) {
return [_imageCache objectForKey:employee.imageName];
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
UIImage *image = [UIImage imageWithContentsOfFile:[self imagePath:employee.imageName]];
dispatch_async(dispatch_get_main_queue(), ^ {
if (image) {
[_imageCache setObject:image forKey:employee.imageName];
cell.imageView.image = image;
} else {
[_imageCache setObject:defaultImage forKey:employee.imageName];
cell.imageView.image = defaultImage;
return;
}
});
});
return cell.imageView.image;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
加载图像需要时间,没有办法让它即时完成。您的代码似乎很合理,您正在从主线程加载图像,因此它不会阻塞 UI,并在加载后缓存它们。使其更快的唯一方法是加载更少的图像或使图像更小。
Loading images takes time, there is no way to make it instant. Your code seems sensible, you are loading the images off the main thread so it will not block the UI, and caching them once loaded. The only way to make it faster is to load less images or make the images smaller.