ios中的資料儲存

2021-07-07 01:25:12 字數 2648 閱讀 4677

ios開發中資料的儲存方式有:

* plist儲存

*偏好設定

*歸檔*sqlite資料庫

*core data

1>  plist儲存

(1) 儲存資料

// plist其實就是儲存字典或者陣列物件

nsarray *arr  = @[@1,@3,@"123"

];// 獲取應用沙盒

//    nsstring *homepath = nshomedirectory();

// 獲取caches

// directory:搜尋哪個資料夾

// domainmask:在哪個範圍內搜尋,在使用者的範圍下 nsuserdomainmask

// expandtilde:是否展開全路徑,yes

nsstring

*cachepath = nssearchpathfordirectoriesindomains(nscachesdirectory, nsuserdomainmask,

yes)[0];

// 拼接檔名arr.plist

// 儲存資料

// file:檔案全路徑

[arr writetofile:filepath atomically:yes];

(1) 讀取資料

// 讀取資料

nsstring

*cachepath = nssearchpathfordirectoriesindomains(nscachesdirectory, nsuserdomainmask,

yes)[0];

// 拼接檔名arr.plist

// 用什麼物件儲存就用什麼物件讀取

nsarray *arr = [nsarray

arraywithcontentsoffile:filepath];

2 >偏好設定儲存

* 偏好設定儲存的本質也是一種plist儲存方式,它主要用來儲存一些鍵值對

(1)資料的儲存

/ nsuserdefaults:用來做偏好設定儲存

// nsuserdefaults使用方式跟字典

// account:xmg age 18

// 偏好設定:如果想要快速進行鍵值對儲存

// 好處:不需要關心檔名

[[nsuserdefaults

standarduserdefaults] setobject:

@"xmg"

forkey:

@"account"];

[[nsuserdefaults

standarduserdefaults] setinteger:

18forkey:

@"age"];

[[nsuserdefaults

standarduserdefaults] setbool:

yesforkey:

@"ison"];

(2)資料的讀取

nsstring

*account = [[

nsuserdefaults

standarduserdefaults] objectforkey:

@"account"];

nsinteger

age = [[

nsuserdefaults

standarduserdefaults] integerforkey:

@"age"];

3 > 

歸檔 (1) 歸檔時

// 歸檔:自定義物件使用歸檔,不能使用plist儲存

person *p = [[person

alloc] init];

p.name = @"xmg";

p.age = 18;

// temp

nsstring *temppath = nstemporarydirectory();

// 拼接檔名

// 歸檔 [

nskeyedarchiver

archiverootobject:p tofile:filepath];

(2)解檔時

// temp

nsstring *temppath = nstemporarydirectory();

// 拼接檔名

// 解檔

person

*p = [

nskeyedunarchiver

unarchiveobjectwithfile:filepath];

(3)需要歸檔的自定義物件中必須遵守nscoding協議,並且必須實現裡面的歸檔和接檔的兩個方法

// 什麼時候呼叫:自定義物件歸檔的時候就會呼叫

// 作用:告訴系統當前物件哪些屬性需要歸檔

- (void)encodewithcoder:(nscoder *)acoder

// 什麼時候呼叫:自定義物件解檔的時候就會呼叫

// 作用:告訴系統當前物件哪些屬性需要解檔

// initwithcoder:解析檔案

// initwithcoder方法呼叫:只要物件是通過解析檔案建立的就會呼叫

- (instancetype)initwithcoder:(nscoder *)adecoder

return self; }

ios中的資料儲存方式

1.nskeyedarchiver 採用歸檔的形式儲存資料,該資料物件需要遵守nscoding協議,並且該物件對於的類必須提供encodewithcoder 和initwithcoder 方法。前乙個方法為編碼的方法,後乙個我解碼的方法。2.nsuserdefaults 類似於android中的sh...

iOS中資料儲存方式

首先我們來了解一下ios中資料儲存有哪些方式 xml 屬性列表 plist 歸檔 plist 全名是 property list,屬性列表檔案。它是一種用來儲存序列化後的物件的檔案。屬性列表檔案的擴充套件名為 plist,因此通常被稱為 plist 檔案。檔案是 xml格式的。它是以 key val...

iOS中的資料的儲存方式

資料庫儲存資料的步驟 什麼是sql語句 sql語句的特點 sql中的常用關鍵字有 select insert update delete from create where desc order by group table alter view index等等 資料操作語句 dml data ma...