在 iOS 的沙盒機制下,妥善管理文件目錄是每個 App 的必修課。本文說明如何存取應用內的資源、取得各標準目錄的路徑,並整理 NSFileManager 的常用檔案與目錄操作方法。
最簡單的方式:由於是沙盒關係,載入打包好的資源時不需要額外指定路徑:
UIImage* image = [UIImage imageNamed:@"11.png"];
需要指定路徑時:可使用 NSBundle 取得程式打包後的路徑:
[[NSBundle mainBundle] resourcePath] // 程式打包後的路徑
若要指定完整路徑,可以自行拼接,或直接用便利方法:
NSString* path = [NSString stringWithFormat:@"%@/%@/%@",
[[NSBundle mainBundle] resourcePath], @"document", @"aaa.txt"];
NSString* path = [[NSBundle mainBundle] pathForResource:@"aaa" ofType:@"png"];
一般應用程式有三個主要目錄:
Documents:用來存放應用相關的資料檔,能與 iTunes 共享存取,且會自動備份到雲端。目前蘋果不建議把大檔案放在這裡,否則備份到 iCloud 會較耗時。
Library/Caches:存放應用支援檔,保存再次啟動時需要資訊,iTunes 不會備份此目錄。一般習慣把影片等較大檔案放在這裡。
tmp:存放臨時檔案,程式終止時可刪除其中的快取內容。
取得自己的 Documents 目錄並組出完整檔案路徑:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDirectory = [paths objectAtIndex:0]; NSString *file = [documentDirectory stringByAppendingPathComponent:@"file1.txt"];
有了 file 路徑,就能用它來建立、讀取與寫入檔案。
-(NSData *)contentsAtPath:path // 從檔案讀取資料 -(BOOL)createFileAtPath:path contents:data attributes:attr // 向檔案寫入資料 -(BOOL)removeItemAtPath:path error:err // 刪除檔案 -(BOOL)moveItemAtPath:from toPath:to error:err // 移動或重新命名(to 不可已存在) -(BOOL)copyItemAtPath:from toPath:to error:err // 複製檔案 -(BOOL)contentsEqualAtPath:path andPath:path2 // 比較兩個檔案內容 -(BOOL)fileExistAtPath:path // 測試檔案是否存在 -(BOOL)isReadableFileAtPath:path // 測試是否可讀 -(BOOL)isWriteableFileAtPath:path // 測試是否可寫 -(NSDictionary *)attributesOfItemAtPath:path error:err // 取得檔案屬性 -(BOOL)setAttributesOfItemAtPath:attr error:err // 更改檔案屬性
-(NSString *)currentDirectoryPath // 取得當前目錄 -(BOOL)changeCurrentDirectoryPath:path // 更改當前目錄 -(BOOL)createDirectoryAtPath:path withIntermediateDirectories:flag attributes:attr // 建立目錄 -(BOOL)fileExistAtPath:path isDirectory:flag // 測試是否為目錄 -(NSArray *)contentsOfDirectoryAtPath:path error:err // 列出目錄內容 -(NSDirectoryEnumerator *)enumeratorAtPath:path // 枚舉目錄內容 -(BOOL)removeItemAtPath:path error:err // 刪除空目錄
+(NSString *)pathWithComponents:components // 依元素組合有效路徑 -(NSArray *)pathComponents // 拆解路徑各部分 -(NSString *)lastPathComponent // 取得最後一部分 -(NSString *)pathExtension // 取得最後一部分的副檔名 -(NSString *)stringByAppendingPathComponent:path // 附加路徑 -(NSString *)stringByAppendingPathExtension:ext // 附加副檔名 -(NSString *)stringByDeletingLastPathComponent // 刪除最後一部分 -(NSString *)stringByDeletingPathExtension // 刪除副檔名 -(NSString *)stringByStandardizingPath // 標準化路徑
NSString* NSUserName(void) // 當前使用者登入名 NSString* NSFullUserName(void) // 當前使用者完整名稱 NSString* NSHomeDirectory(void) // 使用者主目錄 NSString* NSHomeDirectoryForUser(NSString* user) // 指定使用者的主目錄 NSString* NSTemporaryDirectory(void) // 臨時檔案目錄
Documents (NSDocumentDirectory) // 可與 iTunes 共享、自動備份 Library/Caches (NSCachesDirectory) // 支援檔,不備份 tmp (NSTemporaryDirectory()) // 臨時檔,程式終止時可移除 Library/Preferences // 偏好設定檔,用 NSUserDefaults 管理
熟悉這些存取與管理方法,就能在 iOS 的沙盒環境中,井然有序地組織 App 的檔案結構。