IOS data Store-02 Archive multiple objects

Source: Internet
Author: User

1, NSData

1. Introduction

use archiverootobject: ToFile : method you can write an object directly to a file, but sometimes you may want to write multiple objects to the same file, then use the nsdata to archive objects

NSData you can provide temporary storage for some data for subsequent writing to a file, or for storing the contents of a file read from disk. variable data spaces can be created using [nsmutabledatadata]

2. Example

1. Archiving (encoding)

//create a new variable data area nsmutabledata *data = [ Nsmutabledata data];//connect the data area to a Nskeyedarchiver object nskeyedarchiver *archiver = [[[Nskeyedarchiver Alloc] Initforwritingwithmutabledata:data] autorelease];//Start archiving objects, archived data will be stored in nsmutabledata [archiver encodeobject:person1 forkey:@ "Person1"]; [Archiver encodeobject:person2 forkey:@ "Person2"];//archive complete (be sure to call this method) [archiver finishencoding];//write archived data to a file [data
   Writetofile:path Atomically:yes]; 

2. Restore (decode)

//reads data from a file NSData *data = [NSData datawithcontentsoffile:path];//based on data, Resolves to a Nskeyedunarchiver object nskeyedunarchiver *unarchiver = [[Nskeyedunarchiver alloc] initforreadingwithdata:data]; Person *person1 = [Unarchiver decodeobjectforkey:@ "Person1"];
   Person *person2 = [Unarchiver decodeobjectforkey:@ "Person2"];//recovery complete [unarchiver finishdecoding]; 


3. Deep Assignment

Temporarily store person1 data nsdata *data = [Nskeyedarchiver archiveddatawithrootobject:person1];//parse data, generate a new person object student *person2 = [Nskeyedunarchiver unarchiveobjectwithdata:data];//respectively print memory address NSLog (@ "person1:0x%x", Person1); Person1:0x7177a60nslog (@ "person2:0x%x", Person2); Person2:0x7177cf0


IOS data Store-02 Archive multiple objects

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.