您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 圖片快取實戰:為什麼別把 UIImage 直接塞進 plist

編輯:iOS 開發綜合

某次寫 demo 時需要快取相機拍下的照片,同時還得記錄像素尺寸、關鍵點等其他資訊。最直覺的做法就是把資料寫進 .plist,再把 plist 存到沙盒。結果這個看似合理的思路,我一連踩了兩個坑。

第一版:直接把 UIImage 放進字典(失敗)

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];

結果 plist 檔案根本沒生出來。原因很單純:plist 只支援有限幾種基本型別(字串、數字、陣列、字典、NSData、NSDate、布林),UIImage 不在其中,寫檔直接失敗。

第二版:轉成 NSData(能跑,但太慢)

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

取用時再解回來:

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

理論上完全可行,實測也能跑。但問題是:把圖片二進位塞進 plist 會讓檔案急速膨脹,讀檔變慢,連帶拖累其他非圖片資料的顯示。這顯然不是好解法。

最終方案:圖片走檔案,plist 只記路徑

這才是 iOS 該有的做法——圖片獨立存成檔案,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", count_]];

[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];

這個架構的额外好處

除了效能,路徑式儲存還讓「刪除單張圖片」變得容易——只要刪檔案、再從陣列移除該筆記錄即可,不必重寫整個 plist。此外,plist 的內容純文字化後,除錯時用記事本就能看懂的優勢也回來了。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved