ios 歸檔學習筆記

來源:互聯網
上載者:User

標籤:ios

歸檔是指用某種格式來儲存一個或者多個對象,以便以後還原這些對象的過程。


使用xml屬性列表進行歸檔

如果你是對NSString,NSDictionary,NSArray,NSData,NSNumber對象進行歸檔,可以使用類中實現的writeToFile:atomically:方法將資料寫到檔案中。

使用dictionaryWithContentsOfFile 或者arrayWithContentsOfFile,dataWithContentsOfFile,stringWithContentsOfFile方法讀回資料。

使用NSKeyedArchiver歸檔

將各種類型的Object Storage Service到檔案中,不僅僅是字串、數組和字典,有一種更靈活的方法,就是NSKeyedArchiver類建立帶鍵的檔案來完成。

帶鍵的檔案中,每個歸檔的欄位都有一個名稱。歸檔某個對象時,為它提供一個名稱,即鍵。從歸檔中檢索對象時,是根據這個鍵來檢索的。

編碼方法和解碼方法

自訂的類對象不能直接歸檔。因為系統不知道如何進行歸檔。

按照<NSCoding>協議,在類中添加encodeWithCoder方法和initWithCoder方法實現歸檔規範。

encodeWithCoder方法告知歸檔程式如何進行歸檔。initWithCoder方法告知如何解編碼。

前面描述的基本oc類,可以使用encodeObject:forKey進行編碼,decodeObject:forKey來解碼,對於基本的C類型使用如下方法

編碼方法 解碼方法
encodeBool:forKey: decodeBool:forKey:
encodeInt:forKey: decodeInt:forKey:
encodeInt32:forKey: decodeInt32:forKey:
encodeInt64:forKey: decodeInt64:forKey:
encodeFloat:forKey: decodeFloat:forKey:
encodeDouble:forKey: decodeDouble:forKey:

來個例子:

- (void)encodeWithCoder:(NSCoder *)coder{    [coder encodeObject:@"tongxue"  forKey:@"name"];    [coder encodeInt:13 forKey:@"age"];}- (id)initWithCoder:(NSCoder *)aDecoder{    NSString * name = [aDecoder decodeObjectForKey:@"name"];    int age = [aDecoder decodeIntForKey:@"age"];    return self;}




ios 歸檔學習筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.