您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 刪除檔案與資料夾的實作方式

編輯:iOS 開發綜合

刪除檔案在 iOS 中同樣由 NSFileManager 負責。以下從最簡單的一行寫法,談到一個較完整的檔案存取封裝類別。

方法一:直接刪除

if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
    NSLog(@"Removed successfully");
}

方法二:帶錯誤處理的呼叫

NSFileManager *defaultManager = [NSFileManager defaultManager];
[defaultManager removeFileAtPath:tildeFilename handler:nil];

handler 可以接收訊息,例如刪除失敗時透過 fileManager:shouldProceedAfterError: 決定是否繼續。要留意的是 removeFileAtPath:handler: 在近年 iOS 版本已被標記為不建議使用,新專案請改用 removeItemAtPath:error: 並自行處理 NSError。

方法三:封裝成 StorageData 類別

以下這個類別把判斷存在、讀寫、刪除、建立目錄、md5、日期計算等常用操作集中在一起,並示範「以日期分資料夾、以網址 md5 當檔名」的快取策略,同時在無網路時回退到昨日快取。

// StorageData.m
#import <CommonCrypto/CommonDigest.h>
#import "StorageData.h"
#import "xunYi7AppDelegate.h"

@implementation StorageData

#pragma mark - 網路
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { }
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { }
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { }
-(void)connectionDidFinishLoading:(NSURLConnection *)connection { }

+(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;
}

// 先找本地,沒有再抓遠端;遠端失敗則退回昨日快取
+(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;   // 今日快取命中

    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;
}

#pragma mark - 工具
+(NSString *)md5:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, 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;
    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;
}

+(NSString *)dataPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

+(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];
    if ([fileManager createFileAtPath:fileName contents:data attributes:nil]) return YES;
    return NO;
}

+(void)deleteFile:(NSString *)fileName {
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSError *error;
    [fileManager removeItemAtPath:fileName error:&error];
}

#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 *d = [NSDate dateWithTimeIntervalSinceNow:-(2 * (24 * 60 * 60))];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    return [dateFormatter stringFromDate:d];
}

#pragma mark - 目錄
+(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)removeFile:(NSString *)filePath {
    NSError *error;
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    if ([fileManager fileExistsAtPath:filePath]) {
        [fileManager removeItemAtPath:filePath error:&error];
    }
    if (error) NSLog(@"error = %@", error);
}

// 刪除前天的資料夾
+(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);
}
@end

// 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 *)imageName;
+(void)removeUploadImage:(UIImage *)image withName:(NSString *)imageName;
+(NSString *)isFileExists:(NSString *)fullpath;
+(void)removeFile:(NSString *)filePath;
@end

這個封裝有幾處值得改良:一是 remoteFetchData 用了 sendSynchronousRequest,會阻塞呼叫端執行緒,若在主執行緒呼叫將直接凍住 UI,建議改為 NSURLSession 的非同步 API;二是快取檔名用網址 md5 是合理設計,但存成 plist 卻寫入任意回應內容,格式未必是合法 plist,用 NSData 直接存檔更合適;三是 removeUploadImage 的邏輯判斷寫反了(存在時才不刪、不存在時才刪),實用上應改為「存在則刪除」。

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