您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

iPhone Documents 目錄的檔案檢查與刪除

編輯:iOS 技巧大全

寫檔案到 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 ** 並記錄訊息。
  • 關於存到哪裡,有個常被忽略的差異:Documents 的內容預設會被 iCloud/iTunes 備份;Library/Caches 則不會。可重新產生的快取檔(如網路圖片)應放 Caches,使用者產生的文件才放 Documents。
  • 存檔時若想避免覆蓋,可搭配 NSUUID 產生唯一檔名,或是先檢查存在性再決定覆寫或改名。

寫入圖片的話,搭配 [UIImagePNGRepresentation(image)] 或 UIImageJPEGRepresentation(image, quality) 取得 NSData,再 writeToFile:atomically: 即可(PNG 無失真、JPEG 檔案較小,依需求挑選)。

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