最簡單的方式是直接引用打包進 App 的資源(由於沙盒機制,並無傳統的文件夾概念):
UIImage* image = [UIImage imageNamed:@"11.png"];
這已是相對於 App 打包後的路徑,無需額外添加。
若需指定完整路徑,則需用到 NSBundle。程式打包後的路徑可透過 [[NSBundle mainBundle] resourcePath] 取得。你可以自行拼接:
NSString* path = [NSString stringWithFormat:@"%@/%@/%@", [[NSBundle mainBundle] resourcePath], @"document", @"aaa.txt"];
或直接:
NSString* path = [[NSBundle mainBundle] pathForResource:@"aaa" ofType:@"png"];
一般來說,應用程式有三個主要目錄:Documents、Library、tmp。目前 Apple 不建議將大數據保存在 Documents(因其會備份到 iCloud,較為麻煩),一般做法會將視頻等檔案存到 Library/Caches 下;而 tmp 目錄則用於存放臨時檔案,可在退出程式時清空其中的緩存。
在程式中取得自己的 Documents 目錄:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
在此基礎上拼接完整的檔案路徑與名稱:
NSString *file = [documentDirectory stringByAppendingPathComponent:@"file1.txt"];
如此便可用 file 來創建、讀取與寫入檔案。
1. 常見的 NSFileManager 檔案方法
-(NSData *)contentsAtPath:path // 從檔案讀取數據
-(BOOL)createFileAtPath:path contents:(NSData *)data attributes:attr // 向檔案寫入數據
-(BOOL)removeItemAtPath:path error:err // 刪除檔案
-(BOOL)moveItemAtPath:from toPath:to error:err // 重命名或移動檔案(to 不能已存在)
-(BOOL)copyItemAtPath:from toPath:to error:err // 複製檔案(to 不能已存在)
-(BOOL)contentsEqualAtPath:path andPath:path2 // 比較兩個檔案的內容
-(BOOL)fileExistAtPath:path // 測試檔案是否存在
-(BOOL)isReadableFileAtPath:path // 測試檔案是否存在且可讀
-(BOOL)isWriteableFileAtPath:path // 測試檔案是否存在且可寫
-(NSDictionary *)attributesOfItemAtPath:path error:err // 獲取檔案屬性
-(BOOL)setAttributesOfItemAtPath:attr error:err // 更改檔案屬性
2. 使用目錄
-(NSString *)currentDirectoryPath // 獲取當前目錄
-(BOOL)changeCurrentDirectoryPath:path // 更改當前目錄
-(BOOL)createDirectoryAtPath:path withIntermediateDirectories:(BOOL)flag attribute:attr // 創建新目錄
-(BOOL)fileExistAtPath:path isDirectory:(BOOL*)flag // 測試是否為目錄
-(NSArray *)contentsOfDirectoryAtPath:path error:err // 列出目錄內容
-(NSDirectoryEnumerator *)enumeratorAtPath:path // 枚舉目錄內容
-(BOOL)removeItemAtPath:path error:err // 刪除空目錄
3. 常用路徑工具方法
+(NSString *)pathWithComponens:components // 根據元素構造有效路徑
-(NSArray *)pathComponents // 析構路徑,獲得各組成部分
-(NSString *)lastPathComponent // 提取路徑的最後一個部分
-(NSString *)pathExtension // 提取最後一部分的擴展名
-(NSString *)stringByAppendingPathComponent:path // 將 path 添加到末尾
-(NSString *)stringByAppendingPathExtension:ext // 添加擴展名
-(NSString *)stringByDeletingLastPathComponent // 刪除最後一部分
-(NSString *)stringByDeletingPathExtension // 刪除擴展名
-(NSString *)stringByExpandingTileInPath // 將 ~ 展開為主目錄
-(NSString *)stringByStandardizingPath // 標準化路徑
4. 常用路徑工具函數
NSString* NSUserName(void) // 回傳當前用戶登錄名
NSString* NSFullUserName(void) // 回傳完整用戶名
NSString* NSHomeDirectory(void) // 回傳主目錄路徑
NSString* NSHomeDirectoryForUser(NSString* user) // 回傳指定用戶的主目錄
NSString* NSTemporaryDirectory(void) // 回傳可用於創建臨時檔案的目錄
5. 常用的 iOS 目錄
Documents(NSDocumentDirectory):用於寫入應用相關數據檔案,可與 iTunes 共享訪問,並會自動備份到雲端。
Library/Caches(NSCachesDirectory):保存應用再次啟動所需資訊,iTunes 不會備份此目錄。
tmp(NSTemporaryDirectory()):存放臨時檔案,應用不再需要時應主動刪除。
Library/Preferences:包含偏好設置檔案,透過 NSUserDefaults 類進行創建、讀取與修改。