14
我想刪除Documents目錄中包含的所有文件和目錄。如何刪除Documents目錄的內容(而不是Documents目錄本身)?
我相信使用[fileManager removeItemAtPath:documentsDirectoryPath error:nil]方法也會刪除文檔目錄。
有沒有什麼方法可以讓你刪除一個目錄的內容而只留下空目錄呢?
我想刪除Documents目錄中包含的所有文件和目錄。如何刪除Documents目錄的內容(而不是Documents目錄本身)?
我相信使用[fileManager removeItemAtPath:documentsDirectoryPath error:nil]方法也會刪除文檔目錄。
有沒有什麼方法可以讓你刪除一個目錄的內容而只留下空目錄呢?
試試這個:
NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *error = nil;
for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error]) {
[[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
}
斯威夫特3.X
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
guard let items = try? FileManager.default.contentsOfDirectory(atPath: path) else { return }
for item in items {
// This can be made better by using pathComponent
let completePath = path.appending("/").appending(item)
try? FileManager.default.removeItem(atPath: completePath)
}