某次寫 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];
結果 plist 檔案根本沒生出來。原因很單純:plist 只支援有限幾種基本型別(字串、數字、陣列、字典、NSData、NSDate、布林),UIImage 不在其中,寫檔直接失敗。
[info setObject:UIImagePNGRepresentation(myImage) forKey:@"img"];
取用時再解回來:
UIImage *myImg = [UIImage imageWithData:[[myArr objectAtIndex:i] objectForKey:@"img"]];
理論上完全可行,實測也能跑。但問題是:把圖片二進位塞進 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 的內容純文字化後,除錯時用記事本就能看懂的優勢也回來了。