Rex*_*ids 7 iphone caching bundle uikit uiimage
我知道-imageNamed:方法返回一个缓存的UIImage,但问题是我的图像文件存储在'Documents'中,-imageNamed:方法似乎只搜索Bundle ...我目前(不情愿地)使用-imageWithContentsOfFile:从'Documents'获取我的图像,但它不一样...向上/向下缩放包含结果图像的UIImageView是不稳定和笨拙的.缩放包含使用-imageNamed创建的图像的相同UIImageView:然而显得非常流畅.所以,再说一次:如果我不能使用-imageNamed,我如何从我的'Documents'中获取缓存的UIImage?
我对rpetrich提供的答案进行了扩展,并覆盖了imageName:方法以添加更多的替换.它首先搜索主包,然后查看缓存目录.您当然可以将caches目录更改为文档目录.
@interface UIImage (CacheExtensions)
+ (UIImage *)imageNamed:(NSString *)name;
+ (void)clearCache;
@end
#import "UIImage+CacheExtensions.h"
static NSMutableDictionary *UIImageCache;
@implementation UIImage (CacheExtensions)
+ (UIImage *)imageNamed:(NSString *)name
{
id result;
if (!UIImageCache)
UIImageCache = [[NSMutableDictionary alloc] init];
else {
result = [UIImageCache objectForKey:name];
if (result) return result;
}
// First, check the main bundle for the image
NSString *imagePath = [[NSBundle mainBundle] pathForResource:name ofType:nil];
result = [UIImage imageWithContentsOfFileimagePath];
if(result) {
[UIImageCache setObject:result forKey:name];
return result;
}
// If not found, search for the image in the caches directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesImagePath = [[paths lastObject] stringByAppendingPathComponent:name];
result = [UIImage imageWithContentsOfFile:cachesImagePath];
if(result) {
[UIImageCache setObject:result forKey:name];
return result;
}
return nil;
}
+ (void)clearCache
{
[UIImageCache removeAllObjects];
}
@end
Run Code Online (Sandbox Code Playgroud)
最简单的方法是NSMutableDictionary存储缓存的图像和清除缓存方法:
@interface UIImage (CacheExtensions)
+ (id)cachedImageWithContentsOfFile:(NSString *)path;
+ (void)clearCache;
@end
static NSMutableDictionary *UIImageCache;
@implementation UIImage (CacheExtensions)
+ (id)cachedImageWithContentsOfFile:(NSString *)path
{
id result;
if (!UIImageCache)
UIImageCache = [[NSMutableDictionary alloc] init];
else {
result = [UIImageCache objectForKey:path];
if (result)
return result;
}
result = [UIImage imageWithContentsOfFile:path];
[UIImageCache setObject:result forKey:path];
return result;
}
+ (void)clearCache
{
[UIImageCache removeAllObjects];
}
@end
Run Code Online (Sandbox Code Playgroud)
注意:您应该+[UIImage clearCache]从您的didReceiveMemoryWarning方法中调用.此外,clearCache将使缓存中的所有对象无效,而不仅仅是未使用的项目; 需要一个UIImage子类和更复杂的缓存机制来解决这个问题.
UIImages您可以像以前一样缓存自己-imageNamed:。它只是加载它们,然后保留它们。NSDictionary您也可以使用并实现您自己的来保留它们-imageNamed:
但我更关心的是你在扩展方面遇到的麻烦。您的图像如何进入文档,如何缩放它们,以及您是否测试了捆绑包中存储的相同图像文件?我怀疑这-imageNamed:与此有什么关系。我更怀疑诸如捆绑应用了一些压缩的事实(尽管我还没有关于为什么这在实践中很重要的理论)、文件中的差异或程序其余部分的差异在扩展期间发生行为(导致磁盘或 CPU 争用)。缓存不太可能与此问题相关。
我会使用仪器进行一些分析,试图找出不稳定的原因。您是否已充分利用磁盘、CPU、内存?瓶颈是什么?
| 归档时间: |
|
| 查看次数: |
4913 次 |
| 最近记录: |