내 애플리케이션이 HTTP를 통해 이미지가 포함 된 패키지를 다운로드합니다. 문서/디렉토리에 저장되어 표시됩니다.Documents 디렉토리의 이미지 캐싱
나는 [UIImage imageNamed :]가 캐시를 사용하기 때문에 UIImage가 iphone/ipad의 ".../Documents /"디렉토리에있는 이미지를 캐시하는 데 작동하지 않는다고 읽었으며 번들의 이미지). 또한 새 패키지를 다운로드 할 때 캐시를 지울 수 있기를 원합니다.
에서 image.h의
#import <Foundation/Foundation.h>
@interface Image : NSObject
+(void) clearCache;
+(UIImage *) imageInDocuments:(NSString *)imageName ;
+(void)addToDictionary:(NSString *)imageName image:(UIImage *)image;
@end
Image.m에서 나는로드의 성능을 향상시키기 위해 쓴
#import "Image.h"
@implementation Image
static NSDictionary * cache;
static NSDictionary * fifo;
static NSNumber * indexFifo;
static NSInteger maxFifo = 25;
+(void)initialize {
[self clearCache];
}
+(void) clearCache {
cache = [[NSDictionary alloc] init];
fifo = [[NSDictionary alloc] init];
indexFifo = [NSNumber numberWithInt:0];
}
+(UIImage *) imageInDocuments:(NSString *)imageName {
UIImage * imageFromCache = [cache objectForKey:imageName];
if(imageFromCache != nil) return imageFromCache;
NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@", imageName, nil]];
UIImage * result = [UIImage imageWithContentsOfFile:path];
[self addToDictionary:imageName image:result];
return result;
}
+(void)addToDictionary:(NSString *)imageName image:(UIImage *)image {
NSMutableDictionary *mFifo = [fifo mutableCopy];
NSString * imageToRemoveFromCache = [mFifo objectForKey:indexFifo];
[mFifo setObject:imageName forKey:indexFifo];
fifo = [NSDictionary dictionaryWithDictionary:mFifo];
// indexFifo is like a cursor which loop in the range [0..maxFifo];
indexFifo = [NSNumber numberWithInt:([indexFifo intValue] + 1) % maxFifo];
NSMutableDictionary * mcache = [cache mutableCopy];
[mcache setObject:image forKey:imageName];
if(imageToRemoveFromCache != nil) [mcache removeObjectForKey:imageToRemoveFromCache];
cache = [NSDictionary dictionaryWithDictionary:mcache];
}
@end
:
그래서, 여기에 내가 쓴 것입니다 영상. 하지만 구현 방법에 대해서는 잘 모르겠습니다. 나는 반대의 효과를 가지고 싶지 않은 : 나는 오른쪽 maxFifo 값을 선택하는 방법을 모르는
- .
- 메모리 경고를 처리하고 캐시가 삭제 될 때 캐시를 지울 필요가 있다고 생각합니까?
어떻게 생각하십니까? 어색해?
아, 몇 가지 오류를 수정했습니다. 캐시가 전혀 사용되지 않았습니다 (addToDictionary 호출이 누락되었습니다). 그리고 이것은 다른 오류를 지나쳤습니다. –