2012-02-01 36 views
0

我的應用程序通過HTTP下載一個包含圖像的包。它們存儲在Documents /目錄中並顯示。我讀了UIImage沒有在iphone/ipad的「.../Documents /」目錄中緩存圖像的工作(因爲只有[UIImage imageNamed:]使用緩存,它只適用於圖像中的圖像)。另外,我希望能夠在下載新軟件包時清除緩存。圖像緩存文檔目錄中的圖像

所以,這裏是我寫的:

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 

我寫的,以改善負載性能圖片。但我不確定實施。我不希望有相反的效果:

  • 有很多重新複製的(從可變百科到unmutable和對面)
  • 我不知道該如何選擇合適的maxFifo值。
  • 您是否認爲我需要處理內存警告並清除緩存?

您怎麼看?它很尷尬嗎?

PS:我把代碼放在gist.github:https://gist.github.com/1719871

+0

哦,我糾正了一些錯誤。根本沒有使用緩存(缺少對addToDictionary的調用)。這使其他錯誤變得更加明顯。 – 2012-02-01 22:44:10

回答

3

哇......你實現你自己的對象緩存?你先看看NSCache看看它是否適合你的需求?我不相信UIImage符合NSDiscardableContent,所以你必須自己清除緩存或者包裝UIImage,如果你想讓緩存處理內存不足的情況,但正如你在你的問題中提到的那樣,你的當前實施不這樣做)

+0

謝謝,我不知道NSCache。我會用它做一些測試。也許我可以:1)在我的Image類中包裝NSCache。 2)所以我可以刪除我的2 NSDictionary(和nsinteger)。 3)當調用[Image clearCache]時,只需調用NSCache方法[x removeAllObjects]。對我來說似乎更容易。 – 2012-02-01 23:02:23