cocoa提供了兩個處理檔案的通用類:屬性列表和物件編碼
在cocoa中,有一類名為屬性物件(property list)的物件,通常簡寫為plist。 這些屬性列表類是nsarray、nsdictionary、nsstring、nsnumber、nsdate和nsdata,以及他們的可修改形態。
nsdata是乙個物件,所以常規的記憶體管理對它是有效的nsdate *yesterday = [nsdate datewithtimeintervalsincenow: -(24 * 60 * 60)];
nslog(@"yesterday is%@",yesterday);
如果想將資料塊傳遞給乙個函式或方法,可以通過傳遞乙個支援自動釋放的nsdata值來實現,而無需擔心記憶體清理的問題。
集合型屬性列表類(nsarray和nsdictionary)具有乙個-writetofile: atomically: 方法,用於將屬性列表的內容寫入檔案。const char *string = "hi there, this is a c string";
nsdata *data = [nsdata datawithbytes:string length: strlen(string)+1];
nsstring和nsdata也具有-writetofile: atomically: 方法,不過只能寫出字串和資料塊。
atomically控制是否應該首先將檔案內容儲存在臨時檔案中,然後再將臨時檔案和原始檔案交換。這是一種安全機制,如果儲存的過程**現意外不會破壞原始檔案。nsarray *phrase;
phrase = [nsarray arraywithobjects: @"i",@"seem",@"to",@"be",@"a",@"verb",nil];
[phrase writetofile: @"/tmp/verbiage.txt" atomically: yes];
可以是用arraywithcontentsoffile:方法讀取該檔案
nsarray *phrase = [nsarray arraywithcontentsoffile: @"/tmp/verbiage.txt"];
物件可以講它們的例項變數和其他資料編碼為資料塊,然後儲存在磁碟中。這些資料塊以後還可以讀回記憶體中,並且還能基於儲存的資料建立新物件。這個過程被稱為編碼與解碼。
採用nscoding協議,可以使物件實現相同的功能
nscoder是乙個抽象類,它定義了一些有用的方法,有一些具體實現的nscoder子類可以用來編碼和解碼物件,nskeyedarchiver和nskeyedunarchiver@protocol nscoding
- (void) encodewithcoder: (nscoder *) encoder;
- (id) initwithcoder: (nscoder *) decoder;
nsdata *data;
data = [nskeyedarchiver archiveddatawithrootobject: thing1];
thing1 = [nskeyedunarchiver unarchiveobjectwithdata: data];
猜想:內部呼叫了傳進去的物件的encodewithcoder和initwithcoder
鍵/值編碼中的基本呼叫時-valueforkey: 和-setvalue: forkey: 方法。
valueforkey: 會首先查詢以引數名命名(格式為-key或-iskey)的getter方法。對於以上兩個呼叫,valueforkey: 會先尋找-name 和-make方法。如果沒有這樣的getter方法,它將會在物件內尋找名稱格式為_key 和key的例項變數。//訪問car物件的name屬性
nsstring *name = [car valueforkey: @"name"];
nslog(@"%@",name);
-valueforkey在objective-c執行時中使用元資料開啟物件並進入其中查詢需要的資訊。通過使用kvc,沒有相關getter方法也能獲取物件值。
OC學習 檔案操作
oc中檔案的操作可以分為兩類 1 檔案本省的操作 建立 刪除 移動 拷貝等 2 檔案內容的操作 讀 寫等 讀 磁碟 記憶體 寫 記憶體 磁碟 要想學會oc中的檔案操作,我們就要學會兩個類 nsfilemanager 檔案管理類 nsfilehandle 檔案控制代碼類 一 nsfilemanager...
OC學習 檔案讀寫
拿到tmp路徑 nsstring tmppath nstemporarydirectory nslog tmppath 獲取nsfilemanager單例類,用於檔案操作 nsfilemanager filemanager nsfilemanager defaultmanager 用nsfilema...
Python爬蟲學習 檔案儲存
開啟模式 執行操作 r 以唯讀的方式開啟 預設 w 以寫入的方式開啟檔案,會覆蓋已存在的檔案 a 以寫入的模式開啟,如果檔案存在,則在末尾追加寫入 b 以2進製的模式開啟 可讀寫模式 可新增到其他模式中使用 import requests url response requests.get url ...