讀寫、移動、刪除前確認檔案存在,避免例外與錯誤。iOS 提供多種檢查方式,適用場景不同。
// 適用:App Bundle 內的唯讀資源(圖片、Plist、JSON 等)
NSString *path = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"];
if (path) {
// 存在,path 為完整路徑
NSDictionary *config = [NSDictionary dictionaryWithContentsOfFile:path];
} else {
// 不存在於 Bundle
}
特點:自動處理本地化目錄(如 `zh-Hans.lproj/config.plist`)、不需完整路徑、只能查 Bundle 內資源。
// 適用:沙盒任意路徑(Documents、Caches、tmp 等)
NSFileManager *fm = [NSFileManager defaultManager];
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject];
NSString *filePath = [docPath stringByAppendingPathComponent:@"user.plist"];
if ([fm fileExistsAtPath:filePath]) {
NSLog(@"檔案存在");
// 進一步判斷是檔案還是目錄
BOOL isDir = NO;
[fm fileExistsAtPath:filePath isDirectory:&isDir];
if (isDir) NSLog(@"是目錄");
} else {
NSLog(@"檔案不存在");
}
特點:最通用、可區分檔案/目錄、支援完整路徑、效能佳。
// FileUtil.h
@interface FileUtil : NSObject
+ (BOOL)fileExistsAtPath:(NSString *)path;
+ (BOOL)fileExistsInDocuments:(NSString *)fileName;
+ (BOOL)fileExistsInCaches:(NSString *)fileName;
@end
// FileUtil.m
@implementation FileUtil
+ (BOOL)fileExistsAtPath:(NSString *)path {
return [[NSFileManager defaultManager] fileExistsAtPath:path];
}
+ (BOOL)fileExistsInDocuments:(NSString *)fileName {
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject]
stringByAppendingPathComponent:fileName];
return [self fileExistsAtPath:path];
}
+ (BOOL)fileExistsInCaches:(NSString *)fileName {
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject]
stringByAppendingPathComponent:fileName];
return [self fileExistsAtPath:path];
}
@end
// 使用
if ([FileUtil fileExistsInDocuments:@"user.plist"]) {
// 存在
}
- (BOOL)judgeFileExist:(NSString *)fileName {
// 從 Bundle 尋找
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@""];
if (path) return YES;
// 從 Documents 尋找
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [[paths.firstObject stringByAppendingPathComponent:fileName]];
return [[NSFileManager defaultManager] fileExistsAtPath:docPath];
}
- (void)loadImageWithCache:(NSString *)imageName urlString:(NSString *)urlString {
// 1. 定義儲存路徑
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dirPath = [[paths.firstObject stringByAppendingPathComponent:@"ImageCache"]
stringByAppendingPathComponent:imageName];
NSData *imageData = nil;
// 2. 檢查本地快取
if ([[NSFileManager defaultManager] fileExistsAtPath:dirPath]) {
NSLog(@"命中本地快取: %@", dirPath);
imageData = [NSData dataWithContentsOfFile:dirPath];
} else {
NSLog(@"快取未命中,下載: %@", urlString);
// 3. 下載(實際專案請用異步 NSURLSession)
NSURL *url = [NSURL URLWithString:urlString];
imageData = [NSData dataWithContentsOfURL:url]; // 同步示範
if (imageData) {
// 4. 確保目錄存在
NSString *dir = [dirPath stringByDeletingLastPathComponent];
[[NSFileManager defaultManager] createDirectoryAtPath:dir
withIntermediateDirectories:YES
attributes:nil
error:nil];
// 5. 寫入檔案
[imageData writeToFile:dirPath atomically:YES];
}
}
// 6. 顯示
if (imageData) {
self.imageView.image = [UIImage imageWithData:imageData];
}
}
| 方法 | 適用範圍 | 是否區分檔案/目錄 | 效能 | 推薦指數 |
|---|---|---|---|---|
| NSBundle pathForResource: | Bundle 唯讀資源 | 否(僅檔案) | 快 | ⭐⭐⭐⭐⭐ (Bundle資源首選) |
| NSFileManager fileExistsAtPath: | 沙盒任意路徑 | 是 (isDirectory:) | 快 | ⭐⭐⭐⭐⭐ (通用首選) |
| 自定義工具類 | 專案統一封裝 | 視封裝 | 快 | ⭐⭐⭐⭐ (團隊協作推薦) |
| 實例方法封裝 | 單一類別內部 | 視實作 | 快 | ⭐⭐⭐ (快速原型) |