Common ways for iOS app data storage

Source: Internet
Author: User
Tags xml attribute

There are 5 ways in which data data is stored in iOS programs:

XML attribute list (plist) archive

Preference (preference setting)

Nskeyedarchiver Archive (nscoding)

SQLite3

Core Data

Each iOS app has its own app sandbox (the app sandbox is the file system directory) and is isolated from other file systems. Apps must stay in their sandbox, other apps can't access the sandbox

Apply the sandbox's file system directory as shown (assuming that the app's name is called layer)

The root path of the emulator app sandbox is: (Apple is the user name, 7.0 is the emulator version)

/users/apple/library/application Support/iphone simulator/7.0/applications

Application Package : (layer in) contains all the resource files and executable files

Documents: Saves data that needs to be persisted when the app runs, and it backs up the directory when itunes synchronizes the device. For example, a game app can save a game archive in that directory

tmp: Saves the temporary data required to run the app, and then deletes the corresponding file from the directory when it is finished. When the app is not running, the system may also purge files in that directory. itunes does not back up this directory when syncing the device

library/caches: Saves data that needs to be persisted when the app runs, and itunes syncs the device without backing up the directory. Non-critical data with large storage volumes and no backup required

library/preference: Save all your app's preferences, and the iOS settings (settings) app will find the app's settings in that directory. This directory is backed up when itunes syncs the device

1.Documents

There are two common ways to get a sandboxed catalog

The first method:

Stitching the "Documents" string with the sandbox root

Sandbox root directory : nsstring *home = nshomedirectory();

NSString *documents = [Home stringbyappendingpathcomponent: @ "documents"];

Not recommended because a new version of the operating system may modify the directory name

The second method:

Using the Nssearchpathfordirectoriesindomains function

Nsuserdomainmask representative from the user folder to find

YES represents the wavy character "~" in the expanded path

Nsarray *array = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, NO);

In iOS, only one directory matches the parameters passed in, so there is only one element in the collection

NSString *documents = [array objectatindex:0];

2,library/caches

tmp: nsstring *tmp = nstemporarydirectory();

library/caches: (2 ways similar to documents)

Stitching the "Caches" string with the sandbox root

Use the Nssearchpathfordirectoriesindomains function (change the function's 1th parameter to: nscachesdirectory)

3, Library/preference

library/preference: Access to Settings information in this directory through the Nsuserdefaults class

The attribute list is an XML-formatted file that expands to the name plist

If the object is NSString, Nsdictionary, Nsarray, NSData, NSNumber, and so on, you can use the writetofile:atomically: method to write the object directly to the property list file

4.

Archive a Nsdictionary object to a list of plist properties

Encapsulate data into a dictionary

Nsmutabledictionary *dict = [Nsmutabledictionary dictionary];

[Dict setobject:@ "hen" forkey:@ "name"];

[Dict setobject:@ "15013141314" forkey:@ "phone"];

[Dict setobject:@ "forkey:@" "Age"];

Persisting a dictionary to a documents/stu.plist file

[Dict Writetofile:path Atomically:yes];

Successfully written to the documents directory

Read the property list and restore the Nsdictionary object

Reads the contents of the documents/stu.plist, instantiates the Nsdictionary

5.

Many iOS apps support preferences such as saving usernames, passwords, font size, and more, and iOS offers a standard set of solutions to add preferences to your app

Each app has a Nsuserdefaults instance that accesses preferences

For example, save the user name, the font size, whether to log on automatically

nsuserdefaults *defaults = [nsuserdefaults standarduserdefaults];

[Defaults setobject: @ "itcast" forkey:@ "username"];

[Defaults setfloat: 18.0f forkey:@ "Text_size"];

[Defaults setbool: YES forkey:@ "Auto_login"];

Read the Last saved settings

Nsuserdefaults *defaults = [Nsuserdefaults standarduserdefaults];

NSString *username = [Defaults stringforkey: @ "username"];

float textSize = [Defaults floatforkey: @ "Text_size"];

BOOL autologin = [Defaults boolforkey: @ "Auto_login"];

Note: When setting the data, Userdefaults does not write immediately, but instead writes the cached data to the local disk according to the timestamp. So after calling the set method, it is possible that the data has not yet been written to the disk application to terminate. The above problem can be forced by calling the Synchornize method to write

[Defaults synchornize];

6.

If the object is NSString, Nsdictionary, Nsarray, NSData, NSNumber and other types, you can archive and restore directly with Nskeyedarchiver

Not all objects can be archived directly in this way, only objects that comply with the Nscoding protocol can

There are 2 ways to nscoding a protocol:

Encodewithcoder:

This method is called every time the object is archived. In this method, you typically specify how to archive each instance variable in an object, and you can use the Encodeobject:forkey: method to archive instance variables

Initwithcoder:

This method is called every time the object is recovered (decoded) from the file. In this method, you typically specify how to decode the data in a file as an instance variable of an object, and you can use the Decodeobject:forkey method to decode the instance variable

Archive a Nsarray object to Documents/array.archive

Nsarray *array = [Nsarray arraywithobjects:@ "a", @ "B", nil];

[nskeyedarchiver archiverootobject: Array tofile:p Ath];

Recovering (decoding) Nsarray objects

Nsarray *array = [nskeyedunarchiver unarchiveobjectwithfile:p Ath];

Archive an object to documents

@interfacePerson:nsobject<nscoding>@property (nonatomic, copy) NSString*Name: @property (nonatomic, assign)intAge ; @property (nonatomic, assign)floatheight;@endimplementation Person- (void) Encodewithcoder: (Nscoder *) Encoder {[Encoder encodeObject:self.name Forkey:@"name"]; [Encoder encodeInt:self.age Forkey:@" Age"]; [Encoder encodeFloat:self.height Forkey:@"Height"];}- (ID) Initwithcoder: (Nscoder *) Decoder {self.name= [Decoder Decodeobjectforkey:@"name"]; Self.age= [Decoder Decodeintforkey:@" Age"]; Self.height= [Decoder Decodefloatforkey:@"Height"]; returnSelf ;}- (void) Dealloc {[Super Dealloc]; [_name release];}@end 

Archive (encode)

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

Person.name = @ "GL";

Person.age = 27;

Person.height = 1.83f;

[Nskeyedarchiver Archiverootobject:person Tofile:path];

Recovery (decoding)

Person *person = [Nskeyedunarchiver Unarchiveobjectwithfile:path];

If the parent class also complies with the Nscoding protocol, please note that:

Should add a sentence to the Encodewithcoder: method

[Super Encodewithcode:encode];

Ensure that inherited instance variables can also be encoded, which can also be archived

Should add a sentence to the Initwithcoder: method

self = [super Initwithcoder:decoder];

Ensure that inherited instance variables can also be decoded, which can also be restored

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.