iOS Development-Data Persistence (i) "Text file + binary archive"

Source: Internet
Author: User
Tags uikit

Overview

Data persistence is divided into different ways, this chapter mainly briefly shows the data archiving (generally speaking serialization) and the way of writing XML text file. The XML text mode mainly uses the Nsarray or Nsdictionary WriteToFile method, and the data archiving uses the data archiving (serialization) such as Nskeyedarchiver/nskeyedunarchiver.


results show


Program Display


Data file

Note the new version of the iOS emulator directory is not in the same place as the previous directory, where the plist file is an XML file that can be opened for direct viewing, while Archi is an archived binary file.


Process Overview


1. New project, drag the interface, complete the program in addition to the operation of the archive, the specific operation: slightly

2. For XML storage, place the data that needs to be stored in a dictionary or array, and then call WriteToFile to save the data to a file, using the class method initwithcontentsoffile reading the stored data can be

3. The relatively complex point of data archiving requires a new data class that implements the the Nscoding protocol then implements the encoding and decoding of two methods.

4. Place the required data in the object of the data class in step 3 where data storage is required, and then use Nsmutabledata and nskeyedarchiver for data archiving.

5. Slightly


Main codeData Classesh file
  staff.h//  dataxmlarchiver////  Created by God Lin on 14/12/9.//  Copyright (c) 2014 Arbboter. All rights reserved.//#import <Foundation/Foundation.h> @interface staff:nsobject <nscoding>{    nsstring* _nickname;    nsstring* _email;    nsstring* _phone;    nsstring* _sex;    nsstring* _position;} @property (nonatomic, retain) nsstring* _nickname; @property (nonatomic, retain) nsstring* _email; @property (Nonatomic, Retain) nsstring* _phone; @property (nonatomic, retain) nsstring* _sex; @property (nonatomic, retain) nsstring* _position; @end

m file
////staff.m//dataxmlarchiver////Created by God Lin on 14/12/9.//Copyright (c) 2014 Arbboter. All rights reserved.//#import "Staff.h" @implementation staff@synthesize _nickname; @synthesize _email; @synthesize _ phone; @synthesize _sex; @synthesize _position; #pragma nscoding implementation Serialization (archive)-(void) Encodewithcoder: (Nscoder *) acoder{[    Acoder encodeobject:self._nickname forkey:@ "nickname"];    [Acoder encodeobject:self._email forkey:@ "email"];    [Acoder encodeobject:self._phone forkey:@ "Phone"];    [Acoder encodeobject:self._sex forkey:@ "Sex"]; [Acoder encodeobject:self._position forkey:@ "position"];}    -(ID) Initwithcoder: (Nscoder *) adecoder{self._nickname = [Adecoder decodeobjectforkey:@ "nickname"];    Self._email = [Adecoder decodeobjectforkey:@ "email"];    Self._phone = [Adecoder decodeobjectforkey:@ "Phone"];    Self._sex = [Adecoder decodeobjectforkey:@ "sex"];    Self._position = [Adecoder decodeobjectforkey:@ "position"]; return self;} @end 


Program Body Codeh file
  viewcontroller.h//  dataxmlarchiver////  Created by God Lin on 14/12/9.//  Copyright (c) 2014 Arbboter. All rights reserved.//#import <UIKit/UIKit.h> @interface viewcontroller:uiviewcontroller{    iboutlet uitextfield* _textnickname;    Iboutlet uitextfield* _textemail;    Iboutlet uitextfield* _textphone;    Iboutlet uitextfield* _textsex;    Iboutlet uitextfield* _textposition;} @property (nonatomic, retain) uitextfield* _textnickname; @property (nonatomic, retain) uitextfield* _textemail;@ Property (Nonatomic, retain) uitextfield* _textphone; @property (nonatomic, retain) uitextfield* _textsex; @property ( Nonatomic, retain) uitextfield* _textposition;-(ibaction) Onhidekeyboard: (ID) sender;-(ibaction) Onxmlsave: (ID) sender;-(ibaction) Onxmlload: (ID) sender;-(ibaction) Onarchiversave: (ID) sender;-(ibaction) Onarchiverload: (ID) Sender; @end

m file
viewcontroller.m//dataxmlarchiver////Created by God Lin on 14/12/9.//Copyright (c) 2014 Arbboter. All rights reserved.//#import "ViewController.h" #import "Staff.h" @interface Viewcontroller () @end @implementation Viewcontroller@synthesize _textnickname, @synthesize _textemail, @synthesize _textphone; @synthesize _textsex;@ Synthesize _textposition;-(ibaction) Onhidekeyboard: (id) sender{[sender Resignfirstresponder];} -(nsstring*) getdocumentdir{//Get saved file name nsarray* Arraypath = Nssearchpathfordirectoriesindomains (NSDocumentDirectory    , Nsuserdomainmask, YES); return [Arraypath objectatindex:0];}    -(void) textclear{Self._textnickname.text = @ "";    Self._textemail.text = @ "";    Self._textphone.text = @ "";    Self._textsex.text = @ ""; Self._textposition.text = @ "";} XML text saves data, you can save data using an array dictionary, etc.-(ibaction) Onxmlsave: (ID) sender{//Save data to dictionary nsmutabledictionary* dict = [Nsmutabledictiona    Ry Alloc] init];    [Dict setobject:self._textnickname.text forkey:@ "nickname"]; [Dict setobject:self._textemail.text forkey:@ "email"];    [Dict setobject:self._textphone.text forkey:@ "Phone"];    [Dict setobject:self._textsex.text forkey:@ "Sex"];        [Dict setobject:self._textposition.text forkey:@ "position"];    nsstring* pathfile = [self getdocumentdir];        Pathfile = [Pathfile stringbyappendingpathcomponent:@ "Staff.plist"];        Data written to file [Dict writetofile:pathfile Atomically:yes]; uialertview* alert = [[Uialertview alloc] initwithtitle:@ "infomation" message:@ "Save finished" Delegate:nil    cancelbuttontitle:@ "OK" otherbuttontitles:nil];    [Alert show];    Using arc, you do not need to manage memory//[alert release]; [Self textclear];}    -(Ibaction) Onxmlload: (ID) sender{//Get saved file name nsstring* Pathfile = [self getdocumentdir];        Pathfile = [Pathfile stringbyappendingpathcomponent:@ "Staff.plist"];    nsdictionary* dict = [[Nsdictionary alloc] initwithcontentsoffile:pathfile];    Self._textnickname.text = [dict objectforkey:@ "nickname"]; Self._textemail.text = [Dict objectforkey:@ "email"];    Self._textphone.text = [dict objectforkey:@ "Phone"];    Self._textsex.text = [dict objectforkey:@ "sex"];        Self._textposition.text = [Dict objectforkey:@ "position"]; uialertview* alert = [[Uialertview alloc] initwithtitle:@ "infomation" message:@ "Load finished" Delegate:nil    cancelbuttontitle:@ "OK" otherbuttontitles:nil]; [Alert show];}    Archived data-(ibaction) Onarchiversave: (ID) sender{staff* staff = [[Staff alloc] init];    Staff._nickname = Self._textnickname.text;    Staff._email = Self._textemail.text;    Staff._phone = Self._textphone.text;    Staff._sex = Self._textsex.text;        Staff._position = Self._textposition.text;        New binary memory (read/write) nsmutabledata* data = [[Nsmutabledata alloc] init];    Set binary memory data content (read-write) nskeyedarchiver* archiver = [[Nskeyedarchiver alloc] initforwritingwithmutabledata:data];    [Archiver encodeobject:staff forkey:@ "Staff"];        [Archiver finishencoding]; Gets the saved file name nsstring* Pathfile = [selfGetdocumentdir];        Pathfile = [Pathfile stringbyappendingpathcomponent:@ "Staff.archi"];        Save Data (archive) [Data writetofile:pathfile Atomically:yes]; uialertview* alert = [[Uialertview alloc] initwithtitle:@ "infomation" message:@ "Archive finished" Delegate:nil    cancelbuttontitle:@ "OK" otherbuttontitles:nil];    [Alert show]; [Self textclear];}    -(Ibaction) Onarchiverload: (ID) sender{//Get saved file name nsstring* Pathfile = [self getdocumentdir];        Pathfile = [Pathfile stringbyappendingpathcomponent:@ "Staff.archi"];        Read archived files to memory (read only) nsdata* data = [NSData datawithcontentsoffile:pathfile];    Decode memory data (read only) nskeyedunarchiver* unarchiver = [[Nskeyedunarchiver alloc] initforreadingwithdata:data];    staff* staff = [Unarchiver decodeobjectforkey:@ "staff"];        [Unarchiver finishdecoding];    Self._textnickname.text = Staff._nickname;    Self._textemail.text = Staff._email;    Self._textphone.text = Staff._phone;    Self._textsex.text = Staff._sex; Self._textpOsition.text = staff._position; uialertview* alert = [[Uialertview alloc] initwithtitle:@ "infomation" message:@ "Load from Archiver finished" delegate:    Nil cancelbuttontitle:@ "OK" otherbuttontitles:nil]; [Alert show];}    -(void) viewdidload{[Super Viewdidload]; Do any additional setup after loading the view, typically from a nib.}    -(void) didreceivememorywarning {[Super didreceivememorywarning]; Dispose of any resources the can be recreated.} @end


Engineering Code

iOS Development-Data Persistence (i) "Text file + binary archive"

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.