前言
一.獲取沙盒路徑
每個ios應用都有自己專屬的應用沙盒,應用沙盒就是檔案系統中的目錄。但是ios系統會將每個應用的沙盒目錄與檔案系統的其他部分隔離,應用必須待在自己的沙盒裡,並只能訪問自己的沙盒。
沙盒目錄
包含內容
documents
存放應用執行時生成的並且需要保留的資料,icloud同步時會同步該目錄
library/caches
存放應用執行時生成的資料,icloud同步時不會同步該目錄
library/preferences/
存放所有的偏好設定
tmp/
存放應用執行時的臨時資料
獲取檔案路徑:
//兩種獲取應用沙盒路徑的不同方法
nsstring *documentpath = [nshomedirectory() stringbyappendingpathcomponent:@"documents"];
nsstring *cachepath = [nshomedirectory() stringbyappendingpathcomponent:@"library/caches"];
nsstring *preferencespath = [nshomedirectory() stringbyappendingpathcomponent:@"library/preferences"];
nsstring *tmppath = [nshomedirectory() stringbyappendingpathcomponent:@"tmp"];
//nssearchpathfordirectoriesindomains()返回的是乙個陣列,這是因為對於mac os可能會有多個目錄匹配某組指定的查詢條件,但是在ios上只有乙個匹配的目錄
nsstring *documentpath1 = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes).lastobject;
nsstring *cachepath1 = nssearchpathfordirectoriesindomains(nscachesdirectory, nsuserdomainmask, yes).lastobwww.cppcns.comject;
nsstring *tmppath1 = nstemporarydirectory();
讀寫json檔案
處理json資料主要是用了nsjsonserialization這個類,這個類主要有下列三個api:
//傳入乙個json資料,返回乙個foundation物件
+ (id)jsonobjectwithdata:(nsdata *)data options:(nsjsonreadingoptions)opt error:(nserror * _nullable *)error;
//傳入foundation物件,轉化為json資料
+ (nsdata *)datawithjsonobject:(id)obj options:(nsjsonwritingoptions)opt error:(nserror * _nullable *)error;
例項:nsarray *array = @[@1, @2, @3];
nsdictionary *dic = [nsdiction程式設計客棧ary dictionarywithobjectsandkeys:array,@"1",@"dongdong", @"name", nil];
//首先判斷能否轉化為乙個json資料,如果能,接下來先把foundation物件轉化為nsdata型別,然後寫入檔案
if ([nsjsonserialization isvalidjsonobject:dic])
//在讀取的時候首先去檔案中讀取為nsdata類物件,然後通過nsjsonserialization類將其轉化為foundation物件
nsdata *jsondata = [[nsfilemanager defaultmanager] contentsatpath:jsonpath];
naahoutsnmsarray *jsondic = [nsjsonserialization jsonobjectwithdata:jsondata options:1 error:nil];
總結本文標題: ios讀寫json檔案的方法示例
本文位址:
json檔案的讀寫
import json 列表寫入檔案 測試list risk list 將資料寫入檔案 file open risk.json w for i in risk list json i json.dumps i file write json i n file close 從檔案中讀取資料 risk ...
python讀寫json檔案方法示例
python寫入json檔案 首先,我們將python建立乙個字典型別的資料data,打包為json字串格式 接下來,我們將打包好的json str寫入檔案 json str json.dumps data with open data.txt a as f a 表示在不刪除原資料的情況下在檔案末尾...
json讀寫檔案
jsonc 寫配置檔案比較簡單,並且解析配置檔案也比較省事。寫配置檔案 cpp view plain copy include include include include include inc json.h define config file config.json typedef stru...