Ios 如何在没有外部库的情况下在UITableView中缓存图像?
Iam正在尝试缓存图像,而不使用UITableview中的外部库。 但是我没有得到任何结果。我的图片是从URL加载的。我有40多张图片,有没有办法缓存而不是直接加载 我使用以下代码加载图像表单URLIos 如何在没有外部库的情况下在UITableView中缓存图像?,ios,uitableview,url,uiimageview,Ios,Uitableview,Url,Uiimageview,Iam正在尝试缓存图像,而不使用UITableview中的外部库。 但是我没有得到任何结果。我的图片是从URL加载的。我有40多张图片,有没有办法缓存而不是直接加载 我使用以下代码加载图像表单URL - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"cell";
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = @"cell";
cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
{
cell = [[testingTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier]
;
}
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.img.image = [UIImage imageWithData:data];
});
});
return cell;
}
你为什么不使用图书馆?使用UIKit的UIImageView+AFNetworking是一个非常好的方法,它可以从URL异步加载图像,还可以缓存图像 示例代码:
[yourImageView setImageWithURL:youURL placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
您可以使用NSCache,它的工作原理类似于NSMutableDictionary,具有线程安全的优点,还具有一些自动删除策略
根据您的要求,您可以创建它的单例实例:
@interface SharedCache : NSCache
+ (id)sharedInstance;
@end
@implementation SharedCache
- (void) emptyCache{
[self removeAllObjects];
}
-(void) dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(id) init {
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emptyCache) name:UIApplicationDidReceiveMemoryWarningNotification object:[UIApplication sharedApplication]];
}
return self;
}
+(id)sharedInstance
{
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init];
});
return _sharedObject;
}
@end
当然,您应该注意检查图像是否已使用指定的密钥缓存。如果您没有阅读我的问题,请先执行。我不需要任何外部库。你能告诉我如何在我的案例中使用它吗?成功下载图像后,使用图像的url作为键将其添加到缓存中。当你需要图像时,你会询问缓存中是否有该密钥的图像,如果没有,你会下载它,如果有,你会显示它。你是否有任何示例项目或代码的示例副本..因为我是新手我意识到你不想要外部库,但为什么?我同意你的观点,大多数人都不会给出很好的结果,仍然会经历图像丢失或闪烁。这就是我写UIImageLoader的原因。它提供了更多的控制,只有两个文件,所以添加到xcode非常简单。回购协议中有一个很好的样本。