"iOS development objective-c" Data persistence-Files and archives

Source: Internet
Author: User
Tags unpack

There are several ways to persist data in OC, such as writing a file or archiving it. How to write a file we can generally read the data in the file directly. For example, I write the data into a XX.txt document. Only if the data is written successfully, I can read the file directly. However, for some users the key data does not play a secret role, if the need to keep confidential also need to use the archive operation.

Operation of the file

First declare a string NSString * str1 = @ "123456789";

Way One

Direct Use Method:

-(BOOL) WriteToFile: (NSString *) path atomically: (BOOL) useauxiliaryfileencoding: (nsstringencoding) ENC error: ( Nserror * *) error;

Write a OC string into a TXT file:

[str1 writetofile:@ "/users/file path secrecy/str1.txt" Atomically:yes encoding:nsutf8stringencoding error:nil];// Convert the string to a binary data stream before writing to the file.

Way Two

Call method First

-(NSData *) datausingencoding: (nsstringencoding) encoding; Converts the OC string to a binary data stream,

Call Method again

-(BOOL) WriteToFile: (NSString *) pathatomically: (bool) Useauxiliaryfile; Writes the data of the binary stream into the file.

NSData * data2 = [str1 datausingencoding:nsutf8stringencoding]; string to data stream [data2 writetofile:@ "/users/file path secrecy/data2.txt" Atomically:yes];

Both of the above data written to the file are finally read directly in the production Str1.txt and data2.txt documents. Find it in the target path, just as we open the ordinary txt document and we can see it, in fact it is a common txt document. This is the final effect.


Two concepts of archive and archive operations

Deep copy and shallow copy.

The first explanation: like retain, just the reference count of the object plus 1 (just a copy of the pointer), this is called a shallow copy. Create a new object like copy, which is called a deep copy.

The second explanation: just copy this object, there is no sub-object Copy object, this is called shallow copy. Copies both the object and its sub-objects, which are called deep copies .

Archiving is a deep copy.

There are bookmarks in the Bookmarks Manager project of the iOS development Objective-c bookmark Manager. We can also use the archive to operate, we just need to archive the bookmark Manager can be, bookmarks are naturally archived in.

Specific operation

We have only four steps to do, if you do not need to solve the archive, the fourth step of the solution archive can not.

First step: Add a <NSCoding>

In the. h file for each class: @interfaceBookMark: NSObject <NSCoding>

Add a <NSCoding> behind the nsobject.

Step two: Rewrite two methods

In the. m file for each class:

Rewrite an archive method:-(ID) Initwithcoder: (Nscoder *) Adecoder and an archive method:

-(void) Encodewithcoder: (Nscoder *) Acoder. This two method name is fixed and does not need to be called by ourselves, because the system is called automatically when archiving and archiving, and we just need to rewrite it. How do you implement these two methods?

In bookmark bookmarks We do these actions.

Solution Archive   We need to unpack what verse to write in it-(ID) Initwithcoder: (Nscoder *) adecoder{self       = [super init];       if (self) {              _url = [adecoder decodeobjectforkey:@ "url"];              _title = [Adecoder decodeobjectforkey:@ "title"];              _stars = [Adecoder decodeintegerforkey:@ "star"];              _vist = [Adecoder decodeintegerforkey:@ "Traffic"];              _lev = [Adecoder decodeobjectforkey:@ "permission"];       }       return self;} Archive   We need to archive what is written in it-(void) Encodewithcoder: (Nscoder *) acoder{       [acoder encodeobject:_url forkey:@ "url"];       [Acoder encodeobject:_title forkey:@ "title"];       [Acoder encodeinteger:_stars forkey:@ "star"];       [Acoder encodeinteger:_vist forkey:@ "Traffic"];       [Acoder Encodeobject:_lev forkey:@ "permission"];}

In the Bookmark manager Bookmanager We do a similar operation, I do not write in the. h file to say how to operate, directly see the. m file is implemented.

Solution Archive-(ID) Initwithcoder: (Nscoder *) adecoder{self       = [super init];       if (self) {              _array = [Adecoder decodeobjectforkey:@ "Manager"];       }       return self;} Archive-(void) Encodewithcoder: (Nscoder *) acoder{       [Acoder encodeobject:_array forkey:@ "Manager"];}

There are two methods in the above solution Archive and archive:

-(ID) Decodeobjectforkey: (NSString *) key;-(void) Encodeobject: (ID) objv forkey: (NSString *) key;

Isn't it kind of like a dictionary operation? Note the keyword Forkey. The string behind him we can write casually, but to ensure that the method of key between the corresponding relationship and the method of the key within the distinction .

Step Three: Archive operations

We need to add a few bookmarks before implementing the archive operation, and we'll add three more bookmarks using the method described in the "iOS development objective-c" Bookmark Manager Project:

Create a new bookmark for Baidu Bookmanager   * Mybookmanager = [[Bookmanager alloc] init];[ mybookmanageraddbookmarkwithurl:@ "www.baidu.com" withtitle:@ "Baidu" Withstars:3 withvist:123 withlevel:@ "C"];// Create a new Sina bookmark [mybookmanageraddbookmarkwithurl:@ "www.sina.com" withtitle:@ "Sina" withstars:7 withvist:456 withlevel:@ "C"] ;//Create a new Sohu bookmark [mybookmanageraddbookmarkwithurl:@ "www.souhu.com" withtitle:@ "Sohu" Withstars:5 withvist:756 withlevel:@ "C"];

With these three bookmarks as an example can be implemented to achieve the specific archive.

Nsmutabledata * data1 = [[Nsmutabledata alloc] init]; Nskeyedarchiver * Arc1 = [[Nskeyedarchiver alloc] initforwritingwithmutabledata:data1];/* archive */[arc1encodeobject: Mybookmanager forkey:@ "bookmark Manager"]; [Arc1finishencoding]; Seal This step must be before writing the data [data1writetofile:@ "/users/file path confidential/Bookmark class design. txt" atomically:yes];

There are two classes used here:nsmutabledata and nskeyedarchiver. one is to declare a mutable data stream, and one is to create a new instance of the archive. With the above operation, the archive has been completed. Finally, a document called "Bookmark class design. txt" is generated, but we can't open it. The following diagram also confirms that there is content, but not as the above file operation directly see what is the content, and can not open.


With the archive operation, data can be written to a file for persistence, and is still confidential. But we can't see the data. Can't you see the data being written? Obviously there is the operation of the archive, which is already known in the word archive.

Fourth Step: Unpack the archive operation

The operation of the archive is actually very simple, the method of two files implemented in the. m file-(ID) Initwithcoder: (nscoder *) Adecoder can play their part.

NSData * data2 = [[NSData alloc] initwithcontentsoffile:@ "/users/file path confidential/Bookmark class design. txt"]; Nskeyedunarchiver * Uarc1 = [[Nskeyedunarchiver alloc] initforreadingwithdata:data2];/* Solution Archive */bookmanager * BK1 = [Uarc1 de codeobjectforkey:@ "Bookmark Manager"];     [Uarc1finishdecoding]; [Bk1showallbookmark];

①. Declaring a data flow data2 to receive data that was just written in the bookmark class design. txt;

②. Archive, using a class nskeyedunarchivercorresponding to the archive;

③. Use a bookmanager * BK1 object to receive the file "bookmark Manager";

④. Complete the solution file;

⑤. Print out the data of the solution.

Printing results:

2015-08-02 10:45:14.750 3. Bookmark Manager [896:303] URL: www.baidu.com title: Baidu Star: 3 visits: 123 Permissions: c2015-08-02 10:45:14.752 3. Bookmark Manager [ 896:303] Website: www.sina.com title: Sina Star: 7 Visits: 456 permissions: c2015-08-02 10:45:14.753 3. Bookmark Manager [896:303] URL: www.souhu.com title: Sohu Star: 5 Visits: 756 Permissions: C

At this point, the archive and the operation of the archive has been introduced, in fact, it is not difficult to achieve.

Look back and see the concept

In the above introduction of deep and shallow copies of the time there is a sentence: Both copy the object, but also copy its sub-object, this is called a deep copy. Archiving is a deep copy.

In the example above, we archived the Bookmark Manager object, not the bookmark . There are three bookmark objects in the bookmark manager: Baidu, Sina and Sohu, respectively. These three bookmark objects are a child object of the bookmark manager (not an inheritance relationship). This means that we have not only copied the bookmark manager, but also copied the bookmark manager's sub-object-bookmark.

Summarize

In this article we describe some of the basic operations of file and archive, and the solution archive. In these operations it is not difficult to find that the basic steps of these operations are relatively fixed. We only need to follow this procedure to invoke the method to achieve the desired function, to achieve the purpose. This is also a feature of OC, be sure to pay attention to the process.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"iOS development objective-c" Data persistence-Files and archives

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.