IOS data persistence (archiving and anti-archiving)

Source: Internet
Author: User

IOS data persistence (archiving and anti-archiving)

IOS data persistence (archiving and anti-archiving)

Data Persistence is actually to store data on the network or hard disk, which is stored on the local hard disk. The local hard disk of the application is a sandbox, and the sandbox is actually a folder, it contains four folders. These are the Documents, Library, APP package, and tmp folders respectively.

Documents mainly stores files that users have been using for a long time,

The Library contains the Caches and Preferences folders,

(1) Caches stores temporary files and Caches them.

(2) Preferences stores Preferences. For example, whether the program is started for the first time

Tmp is a temporary file, but it is different from Caches,

The APP package contains some compiled files, which cannot be modified.

1. First create a Person class

. H file

# Import

// If You Want To archive a class object, you must make the class compliant with the NSCoding protocol.

@ Interface Person: NSObject

@ Property (nonatomic, copy) NSString * name;

@ Property (nonatomic, copy) NSString * gender;

@ Property (nonatomic, assign) NSInteger age;

-(Id) initWithName :( NSString *) name gender :( NSString *) gender age :( NSInteger) age;

@ End


. M file

# Import "Person. h"

@ Implementation Person

-(Id) initWithName :( NSString *) name gender :( NSString *) gender age :( NSInteger) age

{

Self = [superinit];

If (self ){

// 1. When the object is a string, array, Dictionary, or set, the attribute's semantic attribute is declared as copy

// 2. Use the setter method when defining attributes and assigning values to instance variables.

// 3. Pay attention to attribute Memory Management

Self. name = name;

Self. gender = gender;

Self. age = age;

}

Return self;

}

// When an object is archived, the method of the object is called to archive its own strength variables.

-(Void) encodeWithCoder :( NSCoder *) ACO

{

[ACO derencodeobject: _ nameforKey: @ "name"];

[Ecoderencodeobject: _ genderforKey: @ "gender"];

[ACO derencodeobject: @ (_ age) forKey: @ "age"];

}

// When an object is archived, the method of the object is called to archive the instance variables of the object.

-(Id) initWithCoder :( NSCoder *) aDecoder

{

Self = [superinit];

If (self ){

Self. name = [aDecoder decodeObjectForKey: @ "name"];

Self. gender = [aDecoder decodeObjectForKey: @ "gender"];

Self. age = [[aDecoderdecodeObjectForKey: @ "age"] integerValue];

}

Return self;

}

-(Void) dealloc

{

Self. name = nil;

Self. gender = nil;

[Superdealloc];

}

@ End


Ii. Archive and archive (. m Files) in the main program)

For ease of understanding, TextFiled and other controls are created and written together.

# Import "SecondViewController. h"

# Import "Person. h"

@ InterfaceSecondViewController ()


@ End


@ Implementation SecondViewController


-(Id) initWithNibName :( NSString *) nibNameOrNil bundle :( NSBundle *) nibBundleOrNil

{

Self = [superinitWithNibName: nibNameOrNilbundle: nibBundleOrNil];

If (self ){

// Custom initialization

}

Returnself;

}


-(Void) viewDidLoad

{

[SuperviewDidLoad];

[SelfcustomizeNavigationControl];

// Do any additional setup after loading the view.

Self. view. backgroundColor = [UIColorwhiteColor];

// Create a View Control

// TextFile1

UITextField * firstFiled = [[UITextFieldalloc] initWithFrame: CGRectMake (260, 30)];

FirstFiled. delegate = self;

FirstFiled. tag= 100;

FirstFiled. placeholder = @ "Enter content ";

FirstFiled. autocorrectionType = UITextAutocorrectionTypeNo;

FirstFiled. borderStyle = UITextBorderStyleRoundedRect;

[Self. viewaddSubview: firstFiled];

[FirstFiledrelease];

// TextFile2

UITextField * secondFiled = [[UITextFieldalloc] initWithFrame: CGRectMake (30,154,260, 30)];

SecondFiled. delegate = self;

SecondFiled. tag = 101;

SecondFiled. autocorrectionType = UITextAutocorrectionTypeNo;

SecondFiled. placeholder = @ "show the content of the previous input box ";

SecondFiled. borderStyle = UITextBorderStyleRoundedRect;

[Self. viewaddSubview: secondFiled];

[SecondFiledrelease];

// WriteButton

UIButton * pigeonholeButton = [UIButtonbuttonWithType: UIButtonTypeCustom];

PigeonholeButton. frame = CGRectMake (30,214,100, 30 );

[PigeonholeButtonsetTitle: @ "ARCHIVE" forState: UIControlStateNormal];

[PigeonholeButtonsetTitleColor: [UIColorblueColor] forState: UIControlStateNormal];

[PigeonholeButtonaddTarget: selfaction: @ selector (pigeonholeClick :) forControlEvents: UIControlEventTouchUpInside];

[Self. viewaddSubview: pigeonholeButton];

// ReadButton

UIButton * againstPigeonholeButton = [UIButtonbuttonWithType: UIButtonTypeCustom];

AgainstPigeonholeButton. frame = CGRectMake (190,214,100, 30 );

[AgainstPigeonholeButtonsetTitle: @ "" forState: UIControlStateNormal];

[AgainstPigeonholeButtonsetTitleColor: [UIColorblueColor] forState: UIControlStateNormal];

[AgainstPigeonholeButtonaddTarget: self action: @ selector (againstPigeonholeClick :) forControlEvents: UIControlEventTouchUpInside];

[Self. viewaddSubview: againstPigeonholeButton];

}

// Archive

-(Void) pigeonholeClick :( UIButton *) pigeonholeBtn

{

// 1. Get the content of the input box

UITextField * tf1 = (UITextField *) [self. viewviewWithTag: 100];

UITextField * tf2 = (UITextField *) [self. viewviewWithTag: 101];

// Encapsulate it into a Person object

Person * per = [[Personalloc] initWithName: tf1.textgender: tf2.textage: 18];

// 1. Create an archive object

NSMutableData * data = [NSMutableDatadata];

NSKeyedArchiver * archiver = [[NSKeyedArchiveralloc] initForWritingWithMutableData: data];

// II. Archiving

[ArchiverencodeObject: primary key: @ "Tsummer"];

// 3. The Archive operation is invalid when the archive operation ends.

[ArchiverfinishEncoding];

[Perrelease];

[Archiverrelease];

// 4. Write data to a file

[DatawriteToFile: [selfgetFilePath] atomically: YES];

}

// Archive

-(Void) againstPigeonholeClick :( UIButton *) againstPigeonholeBtn

{

// 1. initialize the NSMutableData object based on the file path

NSMutableData * mData = [NSMutableDatadataWithContentsOfFile: [selfgetFilePath];

// 2. Create an archive object

NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiveralloc] initForReadingWithData: mData];

// 3. Archive

Person * per = [unarchiverdecodeObjectForKey: @ "Tsummer"];

// 4. End the archive

[UnarchiverfinishDecoding];

[Unarchiverrelease];

UITextField * tf1 = (UITextField *) [self. viewviewWithTag: 100];

Tf1.text = per. gender;

UITextField * tf2 = (UITextField *) [self. viewviewWithTag: 101];

Tf2.text = per. name;

NSLog (@ "anti-Archive ");

}

// Obtain the file path

-(NSString *) getFilePath

{

// 1. first obtain the path of the Documents folder

NSString * documentsPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

// (2) concatenate the file path

NSString * newFilePath = [documentsPath stringByAppendingPathComponent: @ "Tsummer.txt"];

NSLog (@ "% @", newFilePath );

Return newFilePath;

}


// Customize navigationControl

-(Void) customizeNavigationControl

{

Self. navigationItem. title = @ "archive and archive ";

}

-(BOOL) textFieldShouldReturn :( UITextField *) textField

{

[TextFieldresignFirstResponder];

ReturnYES;

}

-(Void) didReceiveMemoryWarning

{

[SuperdidReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}


/*

# Pragma mark-Navigation


// In a storyboard-based application, you will often want to do a little preparation before navigation

-(Void) prepareForSegue :( UIStoryboardSegue *) segue sender :( id) sender

{

// Get the new view controller using [segue destinationViewController].

// Pass the selected object to the new view controller.

}

*/


@ End



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.