刪除檔案在 iOS 上靠 NSFileManager 就能完成,但依需求不同有幾種寫法。本文先整理三種常用方式,再附上一份把常用檔案操作(刪除、建立、判斷存在、MD5、圖片存取)統統封裝起來的 StorageData 類,供直接取用。
if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
NSLog(@"Removed successfully");
}
這段 Objective-C 程式碼用於刪除指定路徑的檔案。removeItemAtPath:error: 回傳 BOOL,成功為 YES。
NSFileManager *defaultManager; defaultManager = [NSFileManager defaultManager]; [defaultManager removeFileAtPath:tildeFilename handler:nil];
handler 可以接收訊息回呼。例如刪除失敗時,可以實作 fileManager:shouldProceedAfterError: 決定是否繼續。
需要注意的是,removeFileAtPath:handler: 自 macOS 10.5 起已被標記為 deprecated。新專案請一律改用方法一的 removeItemAtPath:error:。
這個類把 iOS 常見的檔案操作——刪除檔案、刪除資料夾、建立檔案、建立資料夾、判斷檔案是否存在、MD5 計算——全部整理成類方法,另外還包含了網路資料抓取與圖片存取。自己用起來相當順手,特別是「抓遠端資料 → 落地快取 → 網路不可用時退回昨日快取」這套邏輯,在很多列表頁場景都能直接複用。
StorageData.h
#import <Foundation/Foundation.h> @interface StorageData : NSObject <NSURLConnectionDataDelegate, NSURLConnectionDelegate> + (NSMutableData *)remoteFetchData:(NSString *)dataUrl; + (NSMutableData *)localFetchData:(NSString *)dataUrl; + (void)saveUploadImage:(UIImage *)image withName:(NSString *)imageName; + (NSString *)fetchUploadImagePath; + (NSString *)fetchUploadImagePath:(NSString *)imageName; + (void)removeUploadImage:(UIImage *)image withName:(NSString *)imageName; + (NSString *)isFileExists:(NSString *)fullpath; + (void)removeFile:(NSString *)filePath; @end
StorageData.m
#import <CommonCrypto/CommonDigest.h>
#import "StorageData.h"
#import "xunYi7AppDelegate.h"
@implementation StorageData
#pragma mark - NSURLConnection 回呼
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"開始接收 didReceiveData 資料");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"開始接收 didReceiveResponse");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"didFailWithError");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"connectionDidFinishLoading");
}
#pragma mark - 遠端資料抓取
+ (NSMutableData *)remoteFetchData:(NSString *)dataUrl{
NSString *currentDataFilePath =
[[self dataPath] stringByAppendingPathComponent:[self fetchTodayDate]];
currentDataFilePath = [self createDirectory:currentDataFilePath];
currentDataFilePath =
[currentDataFilePath stringByAppendingPathComponent:
[NSString stringWithFormat:@"%@.plist", [self md5:dataUrl]]];
if ([xunYi7AppDelegate isReachable]) {
NSURL *url = [[NSURL alloc] initWithString:dataUrl];
NSURLRequest *request =
[[NSURLRequest alloc] initWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60];
NSURLResponse *response = [[NSURLResponse alloc] init];
NSError *receiveDataError = [[NSError alloc] init];
NSMutableData *receivedData =
(NSMutableData *)[NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&receiveDataError];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
return receivedData;
}
else {
[xunYi7AppDelegate showNetworkMessage];
}
return nil;
}
#pragma mark - 本地快取(含遠端回填)
+ (NSMutableData *)localFetchData:(NSString *)dataUrl{
NSString *currentDataFilePath =
[[self dataPath] stringByAppendingPathComponent:[self fetchTodayDate]];
NSString *yesterdayDataFilePath =
[[self dataPath] stringByAppendingPathComponent:[self fetchYesterdayDate]];
currentDataFilePath = [self createDirectory:currentDataFilePath];
currentDataFilePath =
[currentDataFilePath stringByAppendingPathComponent:
[NSString stringWithFormat:@"%@.plist", [self md5:dataUrl]]];
yesterdayDataFilePath =
[yesterdayDataFilePath stringByAppendingPathComponent:
[NSString stringWithFormat:@"%@.plist", [self md5:dataUrl]]];
NSMutableData *localData = [self fromFilenamePathFetchLocalData:currentDataFilePath];
if (localData != nil) {
return localData; // 今日快取命中
}
else {
NSMutableData *receivedData = [self remoteFetchData:dataUrl];
if (receivedData != nil) {
if ([self storageDataToFile:receivedData fileName:currentDataFilePath]) {
NSLog(@"保存成功");
[self removeDirectory]; // 順手清掉前天的舊資料
}
else {
NSLog(@"保存失敗");
}
}
else {
// 網路抓取失敗,退回昨日快取
if ((localData = [self fromFilenamePathFetchLocalData:yesterdayDataFilePath]) != nil) {
return localData;
}
}
return receivedData;
}
return nil;
}
#pragma mark - MD5
+ (NSString *)md5:(NSString *)str{
const char *cStr = [str UTF8String];
unsigned char result[16];
CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
return [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]];
}
#pragma mark - 圖片存取
+ (void)saveUploadImage:(UIImage *)image withName:(NSString *)imageName{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSError *error;
// 取得沙盒中的 Documents 目錄
NSString *fullPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
fullPath = [fullPath stringByAppendingPathComponent:@"tmpImage"];
if (![fileManager fileExistsAtPath:fullPath]) {
[fileManager createDirectoryAtPath:fullPath
withIntermediateDirectories:YES
attributes:nil
error:&error];
}
fullPath = [fullPath stringByAppendingPathComponent:imageName];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
[imageData writeToFile:fullPath atomically:NO];
}
+ (void)removeUploadImage:(UIImage *)image withName:(NSString *)imageName{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSError *error;
NSString *fullPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
fullPath = [fullPath stringByAppendingPathComponent:@"tmpImage"];
if (![fileManager fileExistsAtPath:fullPath]) {
[fileManager removeItemAtPath:fullPath error:&error];
}
}
+ (NSString *)fetchUploadImagePath:(NSString *)imageName{
NSString *fullPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
fullPath = [fullPath stringByAppendingPathComponent:@"tmpImage"];
fullPath = [fullPath stringByAppendingPathComponent:imageName];
return fullPath;
}
#pragma mark - 判斷與刪除
+ (NSString *)isFileExists:(NSString *)fullpath{
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:fullpath]) {
return fullpath;
}
return nil;
}
+ (void)deleteFile:(NSString *)fileName{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSError *error;
[fileManager removeItemAtPath:fileName error:&error];
}
+ (void)removeFile:(NSString *)filePath{
NSError *error;
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:filePath]) {
[fileManager removeItemAtPath:filePath error:&error];
}
if (error) {
NSLog(@"error = %@", error);
}
}
#pragma mark - 目錄操作
+ (NSString *)dataPath{
// 指定存取路徑為應用程式沙盒的 Documents 目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}
+ (NSString *)createDirectory:(NSString *)directoryName{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSError *error;
if (![fileManager fileExistsAtPath:directoryName]) {
[fileManager createDirectoryAtPath:directoryName
withIntermediateDirectories:YES
attributes:nil
error:&error];
}
return directoryName;
}
+ (void)removeDirectory{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *removeDirectoryPath =
[documentsPath stringByAppendingPathComponent:[self fetchYesterdayBeforeDate]];
NSError *error;
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:removeDirectoryPath]) {
[fileManager removeItemAtPath:removeDirectoryPath error:&error];
}
if (error) {
NSLog(@"error = %@", error);
}
}
#pragma mark - 資料讀寫
+ (NSMutableData *)fromFilenamePathFetchLocalData:(NSString *)filename{
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:filename]) {
NSData *data = [fileManager contentsAtPath:filename];
return [data mutableCopy];
}
return nil;
}
+ (BOOL)storageDataToFile:(NSData *)data fileName:(NSString *)fileName{
NSFileManager *fileManager = [[NSFileManager alloc] init];
return [fileManager createFileAtPath:fileName contents:data attributes:nil];
}
#pragma mark - 日期工具
+ (NSString *)fetchTodayDate{
NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
return [dateFormatter stringFromDate:currentDate];
}
+ (NSString *)fetchYesterdayDate{
NSDate *yesterdayDate = [NSDate dateWithTimeIntervalSinceNow:-(24 * 60 * 60)];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
return [dateFormatter stringFromDate:yesterdayDate];
}
+ (NSString *)fetchYesterdayBeforeDate{
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:-(2 * (24 * 60 * 60))];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
return [dateFormatter stringFromDate:date];
}
@end
同步請求會卡住主執行緒。sendSynchronousRequest:returningResponse:error: 是同步呼叫,若在主執行緒執行會直接凍結 UI。這份程式碼寫於NSURLConnection 盛行的年代,新專案請改用 NSURLSession 的 dataTaskWithRequest:completionHandler:,並搭配非同步回呼。
MD5 不適合當安全機制。這裡用 MD5 只是為了把 URL 轉成固定長度的檔名,避免中文與特殊字元造成路徑問題,這個用途沒問題。但 MD5 已被證明不具備抗碰撞性,切勿用它來儲存密碼或做完整性簽章。
沙盒目錄的選擇。程式碼把資料寫進 Documents,這個目錄會被 iCloud / iTunes 備份。若只是暫時快取,放在 NSCachesDirectory 更合適——系統在空間不足時有權回收它,也不會佔用使用者的備份配額。
錯誤處理偏弱。多處 error 變數未初始化就傳入,會導致後續的 if (error) 判斷失真。實務上應寫成 NSError *error = nil; 再傳 &.amp;error。
如有不盡完善之處,歡迎指正與改進。