寫檔案到 Documents 之前,通常要先確認「這個檔名是否已存在」,並在需要時先清掉舊檔。以下示範以 NSFileManager 完成檢查與刪除的完整流程。
NSFileManager *fileManager = [NSFileManager defaultManager];
// 取得 Documents 目錄路徑
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// 組出完整檔名
NSString *uniquePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"pin.png"];
BOOL blHave = [fileManager fileExistsAtPath:uniquePath];
if (!blHave) {
NSLog(@"no have");
return;
} else {
NSLog(@"have");
BOOL blDele = [fileManager removeItemAtPath:uniquePath error:nil];
if (blDele) {
NSLog(@"dele success");
} else {
NSLog(@"dele fail");
}
}
NSSearchPathForDirectoriesInDomains 回傳的是「陣列」,雖然一般只有一筆,正式寫法仍應做邊界檢查,或直接取 lastObject。removeItemAtPath:error: 的 error 傳 nil 會失去除錯資訊,建議傳入 NSError ** 並記錄訊息。NSUUID 產生唯一檔名,或是先檢查存在性再決定覆寫或改名。寫入圖片的話,搭配 [UIImagePNGRepresentation(image)] 或 UIImageJPEGRepresentation(image, quality) 取得 NSData,再 writeToFile:atomically: 即可(PNG 無失真、JPEG 檔案較小,依需求挑選)。