Plist檔案儲存及沙盒路徑詳解

2021-07-05 21:15:06 字數 2858 閱讀 5875

property list屬性列表檔案

它是一種用來儲存序列化後的物件的檔案。屬性列表檔案的擴充套件名為.plist ,因此通常被稱為 plist檔案。檔案是xml格式的。

plist檔案通常用於儲存使用者設定,也可以用於儲存**的資訊。

<1>工程裡的檔案路徑

nsbundle * bundle = [nsbundle mainbundle];

nsstring * path = [bundle pathforresource:@"plistdocument" oftype:@"plist"];

nslog(@"%@",path);

輸出後的結果 (xcode7)

<2>沙盒裡的檔案路徑

nsarray * patharray = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes);

nslog(@"patharray = %@",patharray);

nsstring * plistpath = [patharray objectatindex:0];

nslog(@"沙盒儲存目錄 = %@",plistpath);

輸出後的結果 (xcode7)

可以看出,xcode7中,直接尋找工程中的plist檔案,輸出的路徑與沙盒路徑一致,即執行後沙盒中提供了相同的plist檔案。

由此可知,這種情況下,我們找到的路徑並非原工程中的路徑,對該路徑下的檔案操作必然也跟工程中的檔案無關了。當需要把資料寫入plist檔案並運用於工程中時,可以先建立檔案並儲存到沙盒中,再移入工程使用;或者直接利用具體路徑在原工程的plist檔案上進行改動。

讀取plist檔案

nsarray * array = [nsarray arraywithcontentsoffile:filepath];

nsdictionary * dictionary = [nsdictionary dictionarywithcontentsoffile:filepath];

預設情況下,每個沙盒含有3個資料夾documentslibrarytmp。因為應用的沙盒機制,應用只能在幾個目錄下讀寫檔案

documents

程式中建立的或在程式中瀏覽到的檔案資料會儲存在該目錄下,itunes備份和恢復的時候會包括此目錄

library

儲存程式的預設設定或其它狀態資訊;

caches

存放快取檔案,itunes不會備份此目錄,此目錄下檔案不會在應用退出刪除

tmp

存放臨時檔案,itunes不會備份和恢復此目錄,此目錄下檔案可能會在應用退出後刪除

注:itunes在與iphone同步時,會備份所有的documents和library檔案。

iphone在重啟時,會丟棄所有的tmp檔案。

那麼我們詳細看一下沙盒目錄的儲存情況:

nsarray * patharray = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes);

nslog(@"patharray = %@",patharray);

進入nsdocumentdirectory發現是列舉型別,nssearchpathdirectory提供了程式執行後各種資料夾路徑

我們看到這幾個時已經很明白了(只列舉部分):

nsdocumentdirectory

nslibrarydirectory

nscachesdirectory

我們需要找什麼目錄,替換nssearchpathfordirectoriesindomains第乙個引數就行了

可能你發現tmp目錄呢?沒找到啊。的確,nssearchpathdirectory裡沒有tmp目錄,可以使用其他的方式尋找:

/** document的上級目錄,即根目錄 */

nshomedirectory()

/** tmp目錄 */

nstemporarydirectory()

// 可以這麼辦

// 或者直接找到tmp目錄下

nsstring * tmppath = nstemporarydirectory();

另外,模擬器目錄和真機目錄的區別

我們用nshomedirectory()輸出一下便知

[[nsuserdefaults standarduserdefaults]

setobject

:obj

forkey

:key];

使用這種方式儲存的資料,放置在 /library/prefereces 下的乙個plist檔案中

若想移除,直接removeobjectforkey或是刪掉沙盒即可

以上只是簡略的說明檔案儲存路徑的問題,檔案管理部分內容將在後續進行補充。

沙盒路徑下Plist檔案操作

存入字典 屬性列表 字串 字典 陣列 data number nsmutabledictionary dict nsmutabledictionary dictionary dict setobject jj forkey name dict setobject nsnumber numberwit...

iOS 獲取沙盒檔案路徑及 寫入 刪除 沙盒檔案

一 沙盒中幾個主要的目錄 每個沙盒下面都有相似的目錄結構,如下圖所示 出自蘋果官方文件 每個應用的沙盒目錄都是相似的,主要包含圖中所示的4個目錄 存放內容 該目錄包含了應用程式本身的資料,包括資源檔案和可執行檔案等。程式啟動以後,會根據需要從該目錄中動態載入 或資源到記憶體,這裡用到了lazy lo...

沙盒檔案儲存

1.plist檔案的訪問 1.1 document的目錄搜尋 1.拼接字串 nsstring homepath nshomedirectory 獲得沙盒路徑 2.系統提供的搜尋 searchpath 搜尋路徑 fordirectories 哪個資料夾 indomains 在哪搜尋 nsstring ...