You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SDWebImage缓存管理:如何识别并删除旧缓存对象?

在SDWebImage中区分并清理旧缓存对象的方案

方法一:利用磁盘缓存文件的修改时间筛选

SDWebImage的磁盘缓存默认存储在Library/Caches/com.hackemist.SDWebImageCache.default目录下,每个缓存图片对应的文件保留着修改时间(即缓存创建/更新的时间)。你可以通过遍历缓存目录,根据时间戳筛选出旧文件:

// 获取SDWebImage的磁盘缓存目录
NSString *cacheDir = [[SDImageCache sharedImageCache] diskCachePath];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *files = [fileManager contentsOfDirectoryAtPath:cacheDir error:nil];

// 设置过期时间,比如7天前
NSTimeInterval expirationTime = 7 * 24 * 60 * 60;
NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-expirationTime];

for (NSString *fileName in files) {
    NSString *filePath = [cacheDir stringByAppendingPathComponent:fileName];
    NSDictionary *fileAttrs = [fileManager attributesOfItemAtPath:filePath error:nil];
    NSDate *modificationDate = fileAttrs[NSFileModificationDate];
    
    // 对比时间,判断是否过期
    if ([modificationDate compare:expirationDate] == NSOrderedAscending) {
        // 删除旧缓存文件
        [fileManager removeItemAtPath:filePath error:nil];
    }
}

方法二:使用SDWebImage内置的缓存清理API

SDWebImage提供了按过期时间清理缓存的封装方法,不需要手动遍历文件,直接调用即可完成旧缓存的识别与删除:

// 清理所有7天前的缓存(默认过期时间就是7天,也可通过修改SDImageCache的config调整)
[[SDImageCache sharedImageCache] deleteOldFilesWithCompletionBlock:^{
    NSLog(@"旧缓存清理完成");
}];

这个方法内部会自动校验缓存文件的修改时间,判断是否过期并执行删除操作,是官方推荐的高效方案。

方法三:自定义缓存键的元数据记录

如果需要更精准的业务级缓存管理(比如按业务规则设置不同的过期时长),可以在缓存图片时额外存储一份包含时间戳的元数据:

// 缓存图片时,同步记录缓存时间
UIImage *targetImage = ...;
NSString *customCacheKey = @"your_business_cache_key";
[[SDImageCache sharedImageCache] storeImage:targetImage forKey:customCacheKey completion:^{
    // 用NSUserDefaults或独立数据库存储缓存时间元数据
    [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:[NSString stringWithFormat:@"cache_timestamp_%@", customCacheKey]];
    [[NSUserDefaults standardUserDefaults] synchronize];
}];

// 后续筛选旧缓存时,读取元数据判断
NSDate *cacheTimestamp = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"cache_timestamp_%@", customCacheKey]];
NSTimeInterval timeElapsed = [[NSDate date] timeIntervalSinceDate:cacheTimestamp];
// 比如判断是否超过3天
if (timeElapsed > 3 * 24 * 60 * 60) {
    [[SDImageCache sharedImageCache] removeImageForKey:customCacheKey withCompletion:nil];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:[NSString stringWithFormat:@"cache_timestamp_%@", customCacheKey]];
}

这种方式适合有特殊业务规则的场景,但需要额外维护元数据,会增加一定的开发复杂度。


内容的提问来源于stack exchange,提问作者Sumeet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 06:32:15