gpt4 book ai didi

ios - 如何在没有外部库的情况下在 UITableView 中缓存图像?

转载 作者:行者123 更新时间:2023-11-29 12:43:37 25 4
gpt4 key购买 nike

我正在尝试在不使用 UITableview 中的外部库的情况下缓存图像。但我没有得到任何结果。我的图片是从 URL 加载的。我有 40 多张图片,有什么方法可以缓存而不是直接加载吗??

我正在使用以下代码加载图片形式的 URL

- (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;
}

最佳答案

您可以使用 NSCache ,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

当然你应该注意检查图像是否已经使用指定的键缓存。

关于ios - 如何在没有外部库的情况下在 UITableView 中缓存图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24229979/

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