Archiving (serialization), anti-archiving (deserialization) of iOS file operations and custom objects

Source: Internet
Author: User

iOS file operations include the creation of files, read-write, move, delete, and so on.

1. Creation of files:

Set the location where the text box stores the file    nsstring *strfilepath=[nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) objectatindex:0];//Specify the file name of the store    nsstring *filename=[strfilepath stringbyappendingpathcomponent:@ "test.txt"];//File Manager <pre name= "code" class= "OBJC" >nsfilemanager *fmaneger=[ Nsfilemanager Defaultmanager];    if ([Fmaneger fileexistsatpath:[self GetFilePath]]) {        self.txtfield.text=[nsstring stringwithcontentsoffile:[ Self GetFilePath] encoding:nsutf8stringencoding Error:nil];    }


2. Writing the file

Write text content    [self.txtField.text writetofile:filename atomically:yes encoding:nsutf8stringencoding Error:nil];    NSLog (@ "Save succeeded");

3. Read the file

Nsfilemanager *fmanager=[nsfilemanager Defaultmanager];    if ([Fmanager fileexistsatpath:filename]) {                [Fmanager createfileatpath:filename contents:nil attributes:nil];    }

4. Movement of files

    Move file    //destination folder    nsstring *destpath=nstemporarydirectory ();    Destination file path    NSString * Destfilepath=[destpath stringbyappendingpathcomponent:@ "test.txt"];        BOOL Result=[fmanager Moveitematpath:filepath Topath:destfilepath Error:nil];    if (result) {        NSLog (@ "move succeeded");    }    else    {        NSLog (@ "Move failed!");    }
5. Deletion of files

Nsfilemanager *fmanager=[nsfilemanager Defaultmanager]; [Fmanager Removeitematpath:filepath Error:nil];

File Operation Summary:

The operation of the file requires the path of the file to be specified before the

Nssearchpathfordirectoriesindomains
To find the file path.

When a file path is obtained or specified, a Nsfilemanager object is required for the creation, movement, and so on of the file.

There are many ways to write a file, basically there are nsstring,nsdictionary, and Nsarray and its subclasses can call the Write method to write the data to the file.

The following is a demonstration of file write and read for the object of the custom class (i.e., archive/reverse archive):

Steps:

1. Define a person class and have the person class implement the Nscoding protocol ( the Protocol must be implemented to implement the archive )

  person.h//  file Operations////  Created by Lifewahaha on 15/5/15.//  Copyright (c) 2015 Lifewahaha. All rights reserved.//#import <Foundation/Foundation.h> @interface person:nsobject<nscoding> @property ( strong,nonatomic) NSString *name; @property (nonatomic) int age;-initwithname: (NSString *) name; @end

2. Implement two Protocol methods in the implementation file of the person class

-(void) Encodewithcoder: (Nscoder *) Acoder

-(ID) Initwithcoder: (Nscoder *) Adecoder

  person.m//  file Operations////  Created by Lifewahaha on 15/5/15.//  Copyright (c) 2015 Lifewahaha. All rights reserved.//#import "Person.h" @implementation person-(ID) initwithname: (NSString *) name{    if ([Super Init ]) {        self.name=name;    }    return self;} #pragma-mark method to convert an object to NSData-(void) Encodewithcoder: (Nscoder *) acoder{    [Acoder encodeObject:self.name forkey:@] Name "];    [Acoder encodeInt:self.age forkey:@ "Age"];} -(ID) Initwithcoder: (Nscoder *) adecoder{    if ([self init]) {        //decompression process        self.name= [Adecoder decodeobjectforkey:@ "name"];        Self.age=[adecoder decodeintforkey:@ "Age"];    }    return self;    } @end

3. In Viewcontroller, import the header file of the person class, and then implement the following method in Viewdidload

-(void) viewdidload {[Super viewdidload];    Person *p=[[person Alloc]init];    [email protected] "a";    p.age=12;    Archive, serialize ****************//1. Create a mutable binary stream nsmutabledata *data=[[nsmutabledata alloc]init]; 2. Create an Archive object (with the ability to convert a custom class into a binary stream) Nskeyedarchiver *archiver=[[nskeyedarchiver alloc]initforwritingwithmutabledata:    Data];    3. Using the Archive object, convert the object of the custom class into a binary stream [archiver encodeobject:p forkey:@ "person"];        4 archive Complete [archiver finishencoding];       Write data to file [data writetofile:[self Getobjfilepath] atomically:yes];        NSLog (@ "%@", data); Anti-archive ****************** nsmutabledata *mdata=[nsmutabledata datawithcontentsoffile:[self    Getobjfilepath]]; 2. Create an anti-archive object that nskeyedunarchiver the binary data into a positive row of OC data *unarchiver=[[nskeyedunarchiver Alloc]initforreadingwithdata:    Mdata];        Person *p2= [unarchiver decodeobjectforkey:@ ' person ']; NSLog (@ "Name:%@", p2.name);
}



Archiving (serialization), anti-archiving (deserialization) of iOS file operations and custom objects

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.