Data persistence and sandbox paths

Source: Internet
Author: User
Tags tmp folder

What is a sandbox mechanism

Simple Object Write file Nsfilemanager complex object write file data persistence What is data persistence? Persistent storage of data Why do you persist data? : Stored in-memory data, program shutdown, memory release, data loss, this data is temporary, the next time users open the application, but also to re-network to refresh the data, undoubtedly increased the user's burden of data persistence nature: Data saved to a file, stored in the sandbox of the program what is the sandbox mechanism? Each application is located in a strictly restricted part of the file system each application can only read files in the file system created for the program each application is placed within the Unified folder directory inside the iOS system. The essence of the sandbox is a folder, the name is randomly assigned Location of the sandbox path 1. The sandbox-relative path to the Finder finder ~/library/application support/iphone Simulator Frequently asked questions in the simulator path that may contain multiple system versions Sandbox mechanism through code lookup program sandbox relative path Nssearchpathfordirectoriesindomains (nssearchpathdirectory directory, Nssearchpathdomainmask Domainmask Domainmask, BOOL Expandtilde) How to get the Sandbox directory path nshomedirectory-----------------------> Sandbox master path nsdocumentdirectory------------------>documents folder Nslibrarydirectory----------------------> Library folder nscachesdirectory---------------------->caches folder nstemporarydirectory ()---------------->tmp folder NSBundle What is the app file within each application folder? How do I get the app file path within each application folder? Get the file path within the Application app folder get application-related configuration properties Two, simple object write file

Writing a String object to a file

Get the Sandbox catalog

NSString *documentspath =nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask, YES). Lastobject;

NSLog (@ "%@", Documentspath);

Method Two

NSString *homepath = Nshomedirectory ();

HomePath = [HomePath stringbyappendingstring:@ "/documents"];

HomePath = [homepathstringbyappendingpathcomponent:@ "Documents"];

NSLog (@ "%@", HomePath);

2. Stitching file path

NSString *filepath = [documentspathstringbyappendingpathcomponent:@ "Abc.txt"];

NSLog (@ "%@", FilePath);

NSString *str = @ "Valentine's Day, race you still alone?" ";

Writes a string in str to a file

[Str writetofile:filepath atomically:yes Encoding:NSUTF8StringEncodingerror:nil];

The above three lines have been implemented. Storing data in the Abc.txt folder for data persistence

NSString *STR2 = [NSString stringWithContentsOfFile:filePathencoding:NSUTF8StringEncoding error:nil];

NSLog (@ "%@", str2);

Array Object Write file

Concatenation of the array txt file behind the folder to enable the addition of arrays

NSString *arrayfilepath = [documentspathstringbyappendingpathcomponent:@ "Array.txt"];

Nsarray *array = @[@ "Tournament", @ "Big mouse", @ "small ultra-Super", @ "small puma", @ "Rhubarb yellow", @ "Popo"];

[Array Writetofile:arrayfilepath atomically:yes];

Nsarray *array2 = [Nsarray Arraywithcontentsoffile:arrayfilepath];

NSLog (@ "%@", array2);

Writing a Dictionary object to a file

The dictionary txt file is spliced behind the folder to implement the dictionary addition

NSString *dictionaryfilepath = [documentspathstringbyappendingpathcomponent:@ "Dictionary.txt"];

Nsdictionary *dictionary = @{@ "Saisai": @ "Race",

@ "Chaochao": @ "super-super",

@ "Doudou": @ "peas"};

[Dictionary Writetofile:dictionaryfilepath Atomically:yes];

Nsdictionary *dictionary2 = [Nsdictionarydictionarywithcontentsoffile:dictionaryfilepath];

NSLog (@ "%@", Dictionary2);

Picture object writing to file

Convert picture resources to NSData type, then save

UIImage *image = [UIImage imagenamed:@ "1.png"];

Convert a picture to NSData

NSData *imagedata = uiimagepngrepresentation (image);

Splicing Data path

NSString *datafilepath = [documentspathstringbyappendingpathcomponent:@ "Image.txt"];

Writing data to a file

[ImageData Writetofile:datafilepath Atomically:yes];

Third, Nsfilemanager

Nsfilemanager, file management, using Detaultmanager, create singleton objects.

You can create folders

You can create, move, copy, delete files

You can tell if a file exists

Nsfilemanager

NSString *path1 = [documentspathstringbyappendingpathcomponent:@ "Path1/path2/path3"];

NSLog (@ "%@", path1);

Create a folder

[[Nsfilemanager Defaultmanager] CreateDirectoryAtPath:path1withIntermediateDirectories:YES attributes:nil Error: NIL];

Determine if a file exists

BOOL B = [[Nsfilemanager Defaultmanager]fileexistsatpath:dictionaryfilepath];

NSLog (@ "%d", b);

Iv. writing files to complex objects

#import

First, create a person class, adhere to the Nscoding protocol, and implement the encoding and de-coding methods in the. m file

@interface person:nsobject<</span>nscoding>

@property (nonatomic, copy) NSString *name;

@property (nonatomic, copy) NSString *gender;

@property (nonatomic, assign) Nsinteger age;

@end

. m file

#import "Person.h"

#define KNAME @ "name"

#define Kgender @ "Gender"

#define Kage @ "age"

@implementation person

Encode #pragma mark

-(void) Encodewithcoder: (Nscoder *) Acoder

{

[Acoder EncodeObject:self.name Forkey:kname];

[Acoder EncodeObject:self.gender Forkey:kgender];

Several properties will be written in a few lines, for the Nsinteger type has a dedicated method

[Acoder encodeInteger:self.age forkey:kage];

}

#pragma mark anti-coding

-(ID) Initwithcoder: (Nscoder *) Adecoder

{

self = [super init];

if (self) {

Self.name = [Adecoder decodeobjectforkey:kname];

Self.gender = [Adecoder Decodeobjectforkey:kgender];

Self.age = [Adecoder decodeintegerforkey:kage];

}

return self;

}

#pragma Mark Dealloc

-(void) dealloc

{

[_name release], _name = nil;//Safe release

[_gender release], _gender = nil; Safe release

[Super Dealloc];

}

@end

Introducing the Person class object in the host controller

#import "JYFViewController.h"

#import "Person.h"

Here is the method

Create Person Object

Person *person = [[Person alloc] init];

Person.name = @ "Puma";

Person.gender = @ "male";

Person.age = 22;

Create a mutable nsmutabledata prepare to hold a person object

Nsmutabledata *persondata = [Nsmutabledata data];

Create an archive tool

Nskeyedarchiver *archiver = [[Nskeyedarchiver alloc]initforwritingwithmutabledata:persondata];

converting to Binary

[Archiver encodeobject:person forkey:@ "PersonKey"];

Complete the conversion

[Archiver finishencoding];

Create path

NSString *personfilepath = [Nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask, YES). lastobjectstringbyappendingpathcomponent:@ "PERSON.ABC"];

Making a write to a NSData object

[Persondata Writetofile:personfilepath Atomically:yes];

Anti-archiving

1. Create a data to accept the information from the person file path

NSData *data = [NSData Datawithcontentsoffile:personfilepath];

2. Use data to create an anti-archiving tool

Nskeyedunarchiver *unarchiver = [[Nskeyedunarchiver alloc]initforreadingwithdata:data];

3. Use tools to turn binary data back into complex objects

Person *p = [Unarchiver decodeobjectforkey:@ "PersonKey"];

4. End anti-archiving

[Unarchiver finishdecoding];

Simple method

Create path

NSString *chaochoafilepath = [Nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask, YES). lastobjectstringbyappendingpathcomponent:@ "Chaochao.avi"];

NSLog (@ "%@", Chaochoafilepath);

Creating objects

Person *chaochao = [[Person alloc] init];

Chaochao.name = @ "Super super";

Chaochao.gender = @ "male";

Chaochao.age = 23;

To save data

[Nskeyedarchiver Archiverootobject:chaochao Tofile:chaochoafilepath];

Read

Person *chaochaoperson = [Nskeyedunarchiverunarchiveobjectwithfile:chaochoafilepath];

NSLog (@ "%@%@%d", Chaochaoperson.name, Chaochaoperson.gender, chaochao.age);

Summarize:

Sandbox mechanism

Simple objects are written to files, only NSString, Nsarray, Nsdictionary, NSData

Complex object writes to file, complies with Nscoding protocol, implements proxy method

Data persistence and sandbox paths

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.