iOS開發-緩存圖片到沙盒 – iPhone手機開發技術文章 iPhone軟體開發教學課程

今天寫一個demo, 涉及圖片緩存操作。

也就是, 把通過照相機拍下來的圖片, 保存到應用中。

因為還涉及瞭其他數據, 包括圖片像素大小, 關鍵點等等等…

所以很自然的想到瞭存儲在.plist文件中, 再把plist文件寫入沙盒。

於是乎..第一次寫的時候, 直接這樣:

NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * namePath = [documentsDirectory stringByAppendingPathComponent:@"gift_info.plist"];
    
    NSMutableArray *myArr = [[NSMutableArray alloc] initWithContentsOfFile:namePath];
    NSMutableDictionary *info = [[NSMutableDictionary alloc]init];
    
    [info setObject:myImage forKey:@"img"];
    [myArr addObject:info];
    [myArr writeToFile:namePath atomically:YES];

這裡的myImage就是我要存儲的UIImage類型的數據。

但是結果呢。很明顯, 這樣是存儲不瞭的(也就是不會生成對應的plist文件)。因為plist文件不能存儲UIImage類型的數據。

犯瞭這個低級錯誤…真是蛋疼。

然後接下去是第二版。

    [info setObject:UIImagePNGRepresentation(myImage)forKey:@"img"];

這裡修改瞭圖片的存儲類型:轉為NSData格式。

然後在要使用圖片的時候, 使用如下語句:

    UIImage *myImg = [UIImage imageWithData:[myArr objectAtIndex:i]objectForKey:@"img"];

這種辦法, 理論上行得通。

但是, 轉為data導致plist文件過大,加載緩慢,影響其他數據的展示。所以也不是一個好辦法。

下面介紹我最後使用的一個辦法。

先把圖片直接存儲到沙盒中。 然後plist文件中記錄圖片的路徑。然後要使用圖片的時候通過訪問plist文件獲取圖片路徑來調用。

下面是使用示例:

一。圖片存儲到沙盒中

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%d.png", myI]];   // 保存文件的名稱
        [UIImagePNGRepresentation(myImage)writeToFile: filePath    atomically:YES];

二。在plist中保存路徑

NSMutableDictionary *info = [[NSMutableDictionary alloc]init];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%d.png", conut_]];   // 保存文件的名稱

[info setObject:filePath forKey:@"img"];
[specialArr addObject:info];

三。使用圖片

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%d.png", (int)current]];   // 保存文件的名稱
UIImage *img = [UIImage imageWithContentsOfFile:filePath];

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *