iOS 沙盒中移動檔案使用 NSFileManager 的 moveItemAtPath:toPath:error:,底層同卷掛載時為元資料操作(極快),跨卷則為複製+刪除。本文涵蓋基礎用法、批次遷移、第三方庫封裝。
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
BOOL success = [fileManager moveItemAtPath:@"/path/src.txt"
toPath:@"/path/dst.txt"
error:&error];
if (success) {
NSLog(@"移動成功");
} else {
NSLog(@"移動失敗: %@", error.localizedDescription);
}
注意:
- (void)migrateDocumentsToCaches {
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
NSString *srcDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject];
NSString *dstDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject];
NSArray *files = [fm contentsOfDirectoryAtPath:srcDir error:&error];
if (!files) return;
for (NSString *fileName in files) {
NSString *src = [srcDir stringByAppendingPathComponent:fileName];
NSString *dst = [dstDir stringByAppendingPathComponent:fileName];
// 若目標已存在,先移除
if ([fm fileExistsAtPath:dst]) {
[fm removeItemAtPath:dst error:nil];
}
if (![fm moveItemAtPath:src toPath:dst error:&error]) {
NSLog(@"遷移失敗 %@ -> %@: %@", src, dst, error.localizedDescription);
}
}
}
GitHub: marcoarment/FCFileManager
// 移動(自動處理目標目錄建立、相對路徑解析)
[FCFileManager moveItemAtPath:@"test.txt" toPath:@"subfolder/test.txt"];
// 刪除
[FCFileManager removeItemAtPath:@"test.txt"];
// 複製
[FCFileManager copyItemAtPath:@"src" toPath:@"dst"];
// 建立目錄
[FCFileManager createDirectoryAtPath:@"deep/nested/folder"];
// 存在性檢查
BOOL exists = [FCFileManager fileExistsAtPath:@"file.txt"];
// 讀寫資料
NSData *data = [FCFileManager readDataAtPath:@"file.dat"];
[FCFileManager writeData:data toPath:@"file.dat"];
優勢:預設相對沙盒 Documents 目錄、鏈式語法、錯誤處理統一、程式碼極簡潔。
@interface SafeFileMover : NSObject
// 安全移動:目標存在則備份、支援進度、可取消
- (void)moveItemAtPath:(NSString *)srcPath
toPath:(NSString *)dstPath
overwrite:(BOOL)overwrite
progress:(void (^)(float progress))progressBlock
completion:(void (^)(BOOL success, NSError *error))completion;
@end
@implementation SafeFileMover
- (void)moveItemAtPath:(NSString *)srcPath
toPath:(NSString *)dstPath
overwrite:(BOOL)overwrite
progress:(void (^)(float))progressBlock
completion:(void (^)(BOOL, NSError *))completion {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
// 1. 目標存在處理
if ([fm fileExistsAtPath:dstPath]) {
if (!overwrite) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(NO, [NSError errorWithDomain:@"SafeMover" code:1 userInfo:@{NSLocalizedDescriptionKey: @"Destination exists"}]);
});
return;
}
// 備份舊檔
NSString *backup = [dstPath stringByAppendingString:@".bak"];
[fm removeItemAtPath:backup error:nil];
[fm moveItemAtPath:dstPath toPath:backup error:nil];
}
// 2. 確保目標目錄存在
NSString *dstDir = [dstPath stringByDeletingLastPathComponent];
[fm createDirectoryAtPath:dstDir withIntermediateDirectories:YES attributes:nil error:&error];
// 3. 執行移動(同卷近乎瞬間)
BOOL ok = [fm moveItemAtPath:srcPath toPath:dstPath error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
completion(ok, error);
});
});
}
@end
| 錯誤代碼 | 常數 | 原因 | 處理 |
|---|---|---|---|
| 4 | NSFileNoSuchFileError | 來源檔案不存在 | 移動前檢查 exists |
| 512 | NSFileWriteFileExistsError | 目標檔案已存在 | 先刪除或設定 overwrite |
| 513 | NSFileWriteNoPermissionError | 無寫入權限 | 檢查沙盒權限、App Groups |
| 516 | NSFileWriteOutOfSpaceError | 磁碟空間不足 | 提示用戶清理空間 |
| 256 | NSFileReadUnknownError | 未知讀取錯誤 | 重試、檢查檔案損壞 |