iOS App 僅能存取自身沙盒目錄。刪除檔案需使用 NSFileManager,注意權限、路徑正確性與錯誤處理。本文整理 3 種核心方法並提供生產級封裝類。
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = @"/path/to/file.txt"; // 完整絕對路徑
NSError *error = nil;
BOOL success = [fileManager removeItemAtPath:filePath error:&error];
if (success) {
NSLog(@"刪除成功: %@", filePath);
} else {
NSLog(@"刪除失敗: %@, 錯誤: %@", filePath, error.localizedDescription);
}
關鍵點:
NSError** 獲取失敗原因(權限不足、檔案不存在、目錄非空等)BOOL 表示結果將 Documents 目錄下所有檔案移至 Caches(或刪除):
- (void)moveAllDocumentsToCaches {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
// 取得 Documents 與 Caches 路徑
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject];
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject];
// 列舉目錄內容
NSArray *contents = [fileManager contentsOfDirectoryAtPath:docPath error:&error];
if (!contents) {
NSLog(@"列舉失敗: %@", error);
return;
}
for (NSString *fileName in contents) {
NSString *srcPath = [docPath stringByAppendingPathComponent:fileName];
NSString *dstPath = [cachePath stringByAppendingPathComponent:fileName];
// 移動(刪除來源)
if (![fileManager moveItemAtPath:srcPath toPath:dstPath error:&error]) {
NSLog(@"移動失敗: %@ -> %@, %@", srcPath, dstPath, error.localizedDescription);
}
}
}
FCFileManager 封裝常用操作,支援相對路徑、鏈式呼叫:
// 移動檔案
[FCFileManager moveItemAtPath:@"test.txt" toPath:@"tests/test.txt"];
// 刪除檔案
[FCFileManager removeItemAtPath:@"test.txt"];
// 其他常用
[FCFileManager copyItemAtPath:@"src" toPath:@"dst"];
[FCFileManager createDirectoryAtPath:@"folder"];
BOOL exists = [FCFileManager fileExistsAtPath:@"file.txt"];
安裝:CocoaPods `pod 'FCFileManager'` 或手動拖入源碼。
整合建立目錄、讀寫、刪除、存在性檢查、MD5 校驗:
// StorageManager.h
@interface StorageManager : NSObject
+ (instancetype)sharedManager;
// 路徑構建
- (NSString *)documentPath:(NSString *)subPath;
- (NSString *)cachePath:(NSString *)subPath;
- (NSString *)tmpPath:(NSString *)subPath;
// 核心操作
- (BOOL)writeData:(NSData *)data toPath:(NSString *)path;
- (NSData *)readDataFromPath:(NSString *)path;
- (BOOL)deleteFileAtPath:(NSString *)path;
- (BOOL)fileExistsAtPath:(NSString *)path;
- (NSDictionary *)fileAttributesAtPath:(NSString *)path;
- (NSString *)md5ForFileAtPath:(NSString *)path;
// 目錄操作
- (BOOL)createDirectoryAtPath:(NSString *)path;
- (NSArray *)listFilesAtPath:(NSString *)path;
- (BOOL)deleteDirectoryAtPath:(NSString *)path;
@end
// StorageManager.m 關鍵實現
- (BOOL)deleteFileAtPath:(NSString *)path {
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
BOOL success = [fm removeItemAtPath:path error:&error];
if (!success) {
NSLog(@"[StorageManager] Delete failed: %@ - %@", path, error.localizedDescription);
}
return success;
}
- (NSString *)md5ForFileAtPath:(NSString *)path {
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
if (!handle) return nil;
CC_MD5_CTX ctx;
CC_MD5_Init(&ctx);
constexpr size_t bufferSize = 1024 * 1024; // 1MB buffer
while (YES) {
NSData *chunk = [handle readDataOfLength:bufferSize];
if (chunk.length == 0) break;
CC_MD5_Update(&ctx, chunk.bytes, (CC_LONG)chunk.length);
}
[handle closeFile];
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5_Final(digest, &ctx);
NSMutableString *md5 = [NSMutableString stringWithCapacity:32];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[md5 appendFormat:@"%02x", digest[i]];
}
return md5;
}
stringByAppendingPathComponent: 而非字串拼接,自動處理 `/`error.code == NSFileNoSuchFileErrordispatch_async(dispatch_get_global_queue(...), ^{ ... })| 目錄 | 取得方法 | 備份策略 | 用途 |
|---|---|---|---|
| Documents | NSDocumentDirectory | iCloud/iTunes 備份 | 用戶產生、需持久化資料 |
| Library/Caches | NSCachesDirectory | 不備份 | 可重建快取、圖片、資料庫 |
| Library/Preferences | NSLibraryDirectory + Preferences | 備份 | NSUserDefaults、設定檔 |
| tmp | NSTemporaryDirectory() | 不備份、重啟可能清空 | 臨時檔、下載中檔案 |