2014年1月28日 星期二
iOS 的資料儲存方式
1. NSUserDefaults
2. plist
3. archiving (封存)
4. SQLite
5. Core Data
APP的 sandbox(沙箱):
除了 NSUserDefaults 外,其他資料保存方式都有同一共同點,也就是應用程式的 /Documents 資料夾。
每一個 APP 都有自己的 /Documents,而 APP 也只能從自己的 /Documents 進行讀寫。
此資料夾存在 /Library 中,在 Mac OS X 10.6 的版本後,Apple 將此資料夾預設為隱藏,
要進入此隱藏資料夾的方法為:
開啟 Finder -> 選擇 “前往” -> "前往資料夾”(快捷鍵:⇧⌘G)-> 輸入 ~/Library
-> Application Support / iPhone Simulator / 版本 / Applications / <UUID> / Documents
在程式中取得 Documents 路徑:
我們可以用以下程式碼來取得 Documents 的參考位址:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDocumentDirectory:我們正在尋找至目錄 Documents 的路徑
NSUserDomainMask:將搜尋限制在我們的 APP sandbox 中
符合的路徑會以 Array 來回傳,且 Documents 目錄會在 Array 中 index 為 0 的位置,
因為每一個 APP 只會有一個 Documents 資料夾。
我們可在剛擷取的路徑後面加上一個字串來建立檔名,
可使用 stringByAppendingString 這個專為此用途設計的 NSString 方法,
NSString *filename = [documentsDirectory stringByAppendingPathComponent :@“theFile.txt”];
呼叫這個方法後,filename 將會包含一個我們 APP 的 Documents 目錄中,theFile.txt 檔案的完整路徑,
此時我們就可以利用 filename 來建立該檔案並進行讀取及寫入
取得 tmp 目錄:
tmp 為 APP 的暫存目錄,要取得其參考位址相對的比 Documents 的要簡單許多,
使用 NSTemporaryDirectory() 這個 Foundation 函式,就可以回傳我們 APP 的 tmp 目錄完整路徑的字串。
想要在暫存目錄建立檔案,我們可以用以下語法:
NSString *tmpfile = [NSTemporaryDirectory() stringByAppendingPathComponent :@"temp.txt”];
訂閱:
文章 (Atom)