使用Three20框架會產生很多的緩存文件,緩存文件存放到應用程序的caches/Three20/文件夾下。時間久了就會占用很大的存儲空間,這時需要提供清空緩存的入口,如在設置界面: 在刪除之前我們需要顯示緩存的大小,提示一下當前緩存是否需要清空: 計算緩存大小的方法如下: [cpp] dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"/Three20/"]; NSFileManager *fileManager = [NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:path]) { NSEnumerator *childEnumber = [[fileManager subpathsOfDirectoryAtPath:path error:nil] objectEnumerator]; unsigned long long folderSize = 0; NSString *fileName; while ((fileName = [childEnumber nextObject]) != nil) { NSString *childFilePath = [path stringByAppendingPathComponent:fileName]; folderSize += [fileManager attributesOfItemAtPath:childFilePath error:nil].fileSize; } dispatch_async(dispatch_get_main_queue(), ^(void){ clearCacheButton.text = [NSString stringWithFormat:@"清空圖片緩存( %0.1f Mb)", (float)folderSize/1000/1000]; [self reloadTableCells]; }); } }); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"/Three20/"]; NSFileManager *fileManager = [NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:path]) { NSEnumerator *childEnumber = [[fileManager subpathsOfDirectoryAtPath:path error:nil] objectEnumerator]; unsigned long long folderSize = 0; NSString *fileName; while ((fileName = [childEnumber nextObject]) != nil) { NSString *childFilePath = [path stringByAppendingPathComponent:fileName]; folderSize += [fileManager attributesOfItemAtPath:childFilePath error:nil].fileSize; } dispatch_async(dispatch_get_main_queue(), ^(void){ clearCacheButton.text = [NSString stringWithFormat:@"清空圖片緩存( %0.1f Mb)", (float)folderSize/1000/1000]; [self reloadTableCells]; }); } }); GCD的使用請參考:iOS多線程編程之Grand Central Dispatch(GCD)介紹和使用 主要是緩存文件過多時計算文件大小需要一定的時間。 清空緩存的方法: [cpp] [[TTURLCache sharedCache] removeAll:YES]; [[TTURLCache sharedCache] removeAll:YES];