iOS notes ——— data storage

Source: Internet
Author: User

Application Sandbox: Application file system root directory, each app has its own sandbox each other; in Xcode, you can print the current app's sandbox root path with the Nshomedirectory () function.

Application Package: Contains all the resource files and execution files;

* Documents: Saves data that needs to be persisted when the app runs, and itunes sync backs up the directory.

* tmp: Save the temporary data generated by the application runtime, and then delete the corresponding files from the directory after use, the application does not run when the system will automatically clear the directory, itunes synchronization will not be backed up by the directory.

* Library/caches: Save data that needs to be persisted when the app runs, itunes does not back up the directory when syncing, generally stores larger data, no backup data.

* Library/preference: Save all your app's preferences, the iOS setting (settings) app will find the app's settings in this directory. When itunes syncs, the directory is backed up.

There are two ways to get the documents directory:

1,nshomedirectory () Gets the root directory of the app and then uses the object method of the NSString class stringByAppendingPathComponent: Stitching documents.

Get to App root nsstring *home = Nshomedirectory (); NSString *path =[home stringbyappendingpathcomponent:@ "Documents"];

2,nssearchpathfordirectoriesindomains () function

Nsuserdomainmask represents the//no from the user folder to represent the wavy character "~" under the path not expanded nsarray *arr = Nssearchpathfordirectoriesindomains ( NSDOCUMENTDIRECTORY,NSUSERDOMAINMASK,NO);//In iOS, only one directory matches the parameters passed in, so there is only one element in this set nsstring *document = [arr OBJECTATINDEX:0];

Get TMP path: nsstring *tmp = Nstemporarydirectory ();

Get library/caches path: nsstring *caches = Nssearchpathfordirectoriesindomains (nscachesdirectory,nsuserdomainmask,no);

Get library/preference: Get information through the Nsuserdefaults class.

Common data storage methods for iOS apps are:

* XML attribute list (plist) archive;

* Preference (preference setting);

* Nskeyedarchiver archive (nscoding);

* SQLite3

* Core Data;

XML attribute list

is an XML-formatted file that expands to the name plist. If the object is a type Nsstring\nsdictionary\nsarray\nsdata\nsnumber,

You can call the Writetofile:aomically: method to write the object to the Plist file.

 

Nsmutabledictionary *dict = [Nsmutabledictionary dictionary]; [Dict setobject:@ "Jack" forkey:@ "name"]; [Dict setobject:@ "1223244" forkey:@ "Phone"];//filepath can documens the path or other paths in the sandbox; [Dict writetofile:filepath atomically: yes];//read plist file; nsdictionary *dict = [Nsdictionary Dictionarywithcontentsoffile:filepath];

Preference (Preferences): Many iOS apps support preferences such as saving usernames, passwords, font sizes, and more. Each app has an instance of Nsuserdefaults that accesses preferences.

Storage preference Content Nsuserdefaults *defaluts = [Nsuserdefaults standarduserdefaults]; [Defaults setobject:@ "Jack" forkey:@ "UserName"]; [Defaults setfloat:190.1f forkey:@ "height"]; [Defaults setbool:yes forkey:@ "Autologin"];//get preference content nsuserdefaults *defaults = [Nsuserdefaults standarduserdefaults ]; NSString *username = [Defaults stringforkey:@ "UserName"];float height = [defaults floatforkey:@ "height"]; BOOL autologin = [Defaults boolforkey:@ "Autologin"];

* Note: Nsuserdefaults data is not written immediately, but the data in the cache is periodically written to the local disk based on the timestamp, so the data may not be written to the disk application until the set method is called.

You can call the Synchronize method to force the write if the above problem occurs.

[Defaults synchronize];

Nskeyedarchiver Archive (nscoding)

* If the object is NSString, Nsdictionary, NSData, Nsarray, NSNumber, etc., it can be archived and restored directly with Nskeyedarchiver.

* Other objects are subject to the Nscoding protocol.

* Two methods of Nscoding protocol:

· Encodewithcode: This method is called every time an object is archived. In this method, you typically specify how to archive each instance variable in an object, which can be archived using Encodeobject:forkey:\encodeint:forkey: And so on.

· Initwithcoder: This method is called every time you restore (decode) from a file. This method specifies how to decode the data in a file into an instance variable of an object. You can decode instance variables by using the Decodeobject:forkey\decodeint:forkey: method.

//Create Person Object Compliance nscoding protocol Person.h @interface person:nsobject@property (copy, nonatomic) NSString *name, @property (assign,nonatomic) int age, @end person.m#import "Person.h" @implementation person-(    void) Encodewithcoder: (Nscoder *) acoder{[acoder encodeObject:self.name forkey:@ "name"]; [Acoder encodeInt:self.age forkey:@ "Age"];} -(ID) Initwithcoder: (Nscoder *) adecoder{if (self = [super init]) {self.name = [Adecoder decodeobjectforkey        : @ "name"];    Self.age = [Adecoder decodeintforkey:@ "age"]; } return self;} @end//Get archive path file Filepathperson *p = [[Peron alloc] init];p. Name = @ "Jack";p. Age = 10; NSString *doc = [Nssearchpathfordirectoriesindomains (Nsdocumentdirectiory,nsuserdomainmask,yes) lastObject]; NSString *filepath = [Doc stringbyappendingpathcomponent:@ "Person.data"];//object archive [Nskeyedarchiver archiveRootObject:p tofile:filepath];//read object from filePath person *p1 = [Nskeyedunarchiver Unarchiveobjectwithfile:filepath]; 

Note: If the parent class of the object also complies with the Nscoding protocol,

In implementing Encodewithcoder: The method should call [Super Encodewithcoder:acoder];

Implement Initwithcoder: The method should call self = [super Initwithcoder:acoder];

Ensure that the continuation of the member variable can be archived and reconciled.

NSData

* Use Archiverootobject:tofile: Method can write an object directly to a file, but many times need to write multiple objects simultaneously to a file, then use the NSData to archive.

* NSData can provide temporary storage space for some data for subsequent writing to the file, or to store the contents of the file read from disk. You can use [Nsmutabledata data] To create variable data spaces;

  

  

Archive (encode)

Create a new variable data area nsmutabledata *data = [nsmutabledata data];//connect data to a Nskeyedarchiver object nskeyedarchiver *archiver = [[ Nskeyedarchiver Alloc] initforwrittingwithmutabledata:data];//Start archiving objects, the stored data is archived into data [archiver Encodeobject:person1 forkey:@ "Person1"]; [Archiver encodeobject:person2 forkey:@ "Person2"];//archive complete. Be sure to call the Finishencoding method [Archiver finishencoding];//to write the archived data to the file [data Writetofile:filepath Atomically:yes];

De-file (decode)

Get data from a file NSData *data [NSData datawithcontentsoffile:filepath];//According to the data obtained, Resolves to a Nskeyedunarchiver object nskeyunarchiver *unarchiver = [[Nskeyedunarchiver alloc] initforreadingwithdata:data]; Person *P1 = [Unarchiver decodeobjectforkey:@ "Person1"]; Person *P2 = [Unarchiver decodeobjectforkey:@ "Person2"];//recovery complete [unarchiver finishdecoding];

Deep replication with archiving

Temporarily stores a Person1 object NSData *data = [Nskeyedarchiver archivedatawithrootobject:person1]; Person *person2 = [Nskeyedunarchiver unarchiveobjectwithdata:data];

iOS notes ——— data storage

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.