Using NSKeyedArchiver to store custom data model

后端 未结 3 1901
星月不相逢
星月不相逢 2021-02-06 00:45

I\'m working on a rss reader. It is just a tableview and each cell shows a custom data model RSSEntry. And I have a NSMutableArray allEntries which contains all RSSEntry I got f

3条回答
  •  孤独总比滥情好
    2021-02-06 00:58

    Place all the entries you want to store into an NSArray and use this code:

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:entries];
    

    Where entries is your array of entries. Nice and easy, just one line of code.

    To unarchive, just use

    NSArray *entries = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    

    NSKeyedArchiver is able to archive any data structure, even a very complex one, of Objective-C objects that implement the NSCoding protocol, including nested NSArrays, NSDictionarys, and custom objects, to a file. NSKeyedUnarchiver does the reverse, taking any data produced by NSKeyedArchiver and reestablishing the original object graph that was archived. Technically, they could just be a single class, but Apple decided to separate them by functionality because this is more grammatically correct or something :)

    I assume you are able to write the resulting NSData object to a file, and read it back again.

提交回复
热议问题