iOS Development--ui Advanced (11) application sandbox, archive, profile, preferences, plist storage, NSData, custom object Archive solution

Source: Internet
Author: User
Tags xml attribute

1. The common way of iOS app data storage
XML attribute list (plist) archive
Preference (preference setting)
Nskeyedarchiver Archive (nscoding)
SQLite3
Core Data

2. Application Sandbox
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, 8.0 is the emulator version)
/users/apple/library/application Support/iphone simulator/8.0/applications

3. Application of sandbox structure analysis
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


4. plist file
1.plist storage, generate a plist file.
2.plist is not an array or a dictionary, plist storage is used to store dictionaries or arrays.
Note: plist cannot store custom objects

5, the application of the common way to get the sandbox directory
Get sandbox path
1, Nshomedirectory ()

2, tmp:nsstring *tmp = Nstemporarydirectory ();

3. Library/caches: (2 ways similar to documents)
Stitching the "Caches" string with the sandbox root
Use the Nssearchpathfordirectoriesindomains function (change the function parameter to: nscachesdirectory)

//directory: Which folder to get//Domainmask: in which range to search, Nsuserdomainmask: means to find on the user's phone//Expandtilde: Whether to expand full path YES: To expand the full path No: Does not expand the full path, the path of the application sandbox is replaced with a tilde (~)//get to the caches folder pathNSString *cachepath = Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) [0]; //Stitching file nameNSString *filepath = [CachePath stringbyappendingpathcomponent:@"arr.plist"]; //1, storage plist,file: The full path of the file[arr Writetofile:filepath atomically:yes]; //2, read plist, what type of storage before, read is whatNsarray *arr = [Nsarray Arraywithcontentsoffile:filepath];

4, Library/preference: Through the Nsuserdefaults class access to the directory settings information

6. Attribute List
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


7. Attribute List-Archive nsdictionary
Archive a Nsdictionary object to a list of plist properties

//encapsulate data into a dictionaryNsmutabledictionary *dict =[Nsmutabledictionary dictionary]; [Dict setobject:@"Hens"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];

8. Attribute List-Restore nsdictionary

Read the property list and restore the Nsdictionary object

9. Preference Settings
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
Make preferences in a dictionary, using the same dictionary.
Preferences benefits: 1. No need to care about file name 2. Fast Key-value pair storage 3. Direct storage of basic data types

Save:

    //get a single caseNsuserdefaults *defaults =[Nsuserdefaults Standarduserdefaults]; //@ "123" Key:pwd[Defaults setobject:@"123"Forkey:@"pwd"]; //BOOL[Defaults setbool:yes Forkey:@"IsOn"]; //int[Defaults Setinteger:TenForkey:@"Num"];

It's easy to read.

    // using nsuserdefaults single case   NSString *pwd = [[Nsuserdefaults standarduserdefaults] Objectforkey:@ "pwd"];    = [[Nsuserdefaults standarduserdefaults] Integerforkey:@ "num"];

10, NSData
Use the Archiverootobject:tofile: method to write an object directly to a file, but sometimes you might want to write multiple objects to the same file, then use NSData to archive the object
NSData can provide temporary storage for some data for subsequent writing to a file, or for storing the contents of a file read from disk. Variable data spaces can be created using [Nsmutabledata data]
Figure

1) nsdata-Archive 2 person objects into the same file

Archive (encode)

//Create a new variable data areaNsmutabledata *data =[Nsmutabledata data];//to connect a data area to a Nskeyedarchiver objectNskeyedarchiver *archiver =[[[ Nskeyedarchiver alloc] initforwritingwithmutabledata:data] autorelease];//Start archive object, archived data will be stored in Nsmutabledata[Archiver encodeobject:person1 Forkey:@"Person1"]; [Archiver encodeobject:person2 Forkey:@"Person2"];//Archive Complete (be sure to call this method)[Archiver finishencoding];//writing archived data to a file[Data Writetofile:path Atomically:yes];

2) nsdata-recover 2 person objects from the same file

Recovery (decoding)

// reading data from a file NSData *data = [NSData Datawithcontentsoffile:path]; // parse into a Nskeyedunarchiver object based on the data Nskeyedunarchiver *unarchiver =*person1 = [unarchiver decodeobjectforkey:@ "person1" *person2 = [unarchiver decodeobjectforkey:@ "person2"];  // Recovery Complete [Unarchiver finishdecoding];

3) deep replication with archiving
For example, a deep copy of a person object

// temporary storage of person1 data NSData *data = [Nskeyedarchiver archiveddatawithrootobject:person1]; // parse data to generate a new person object Student *person2 = [Nskeyedunarchiver unarchiveobjectwithdata:data]; // Print memory addresses separately NSLog (@ "person1:0x%x"//  person1:0x7177a60NSLog (@ " person2:0x%x " // person2:0x7177cf0

Archive:
Storing a custom object

Person *p =[[Person alloc] init]; P.age= -; P.name=@"a"; //Get the TEM folder pathNSString *temppath =nstemporarydirectory (); //Stitching file nameNSString *filepath = [TempPath stringbyappendingpathcomponent:@"Person.data"]; //Nskeyedarchiver is specifically designed to be used for custom object archiving[Nskeyedarchiver archiverootobject:p Tofile:filepath];

In PERSON.M

// When to call: This method is called when an object is to be archived. // function: Tell Apple which attributes in the current object need to be archived -(void) Encodewithcoder: (Nscoder *) acoder{    [Acoder encodeobject:_ Name Forkey:@ "name"];    [Acoder encodeint:_age Forkey: @"  Age " ];}

Solution file:

    // Get the TEM folder path    NSString *temppath = nstemporarydirectory ();         // Stitching file name    NSString *filepath = [TempPath stringbyappendingpathcomponent:@ "person.data"];    //  solution person   *p = [Nskeyedunarchiver Unarchiveobjectwithfile:filepath];

When to call: This method is called when an object is going to be unpacked.

//action: Tell Apple which attributes in the current object need to be unpacked//Initwithcoder when to invoke: Whenever a file is parsed, it is called- (ID) Initwithcoder: (Nscoder *) adecoder{#warning[Super Initwithcoder]//You cannot use [super Initwithcoder] and when to invoke [Super Initwithcoder:adecoder]: As long as the parent class complies with the Nscoding protocol, it calls the    if(self =[Super Init]) {        //solution file//Be sure to remember to assign values to member properties_name = [Adecoder decodeobjectforkey:@"name"]; _age= [Adecoder Decodeintforkey:@" Age"]; }    returnSelf ;}

11. Data storage (data persistence)
1> 5 ways to introduce iOS data storage
2> Introduction App Sandbox (application's folder)
• How do I find the path to the application sandbox? First, you need to show hidden files.
• Click to go to personal resources----->application Support->iphone simulator->7.1-> There are all application sandbox
3> application Sandbox How many folders to save, in which folder. Describes each folder in the sandbox.

12.plist Storage
• Store some of the system's own OC object generation pilst files.
1> Understanding Data storage: Data storage typically has two operations, one save, one fetch. Drag two buttons, one to save, one to take
2> plist Storage principle:
• Plist storage can be performed as long as there are writetofile objects, and WriteToFile can be automatically generated in plist format.
• Commonly used foundation objects have this method, arrays, dictionaries, strings, etc.
3> how to write to the sandbox, you need to get the sandbox path.
• Get Documents Path
• Stitching the file name because the data is written to the file, not written to the folder. Paths passed/separated, in order to avoid writing/, will use Stringbyappendingpathcompent, automatically between the folder and file Add/.
4> How to read, what type of storage is stored, read out what type, directly with the type of storage, parse the file is good, with contentsoffile parsing.
5> Note that the Plist store cannot store custom objects and will fail.

13> Preference Settings
1> what is a preference store: it is to save some basic information, account number, password, status.
2> Preferences principle: Do not need to care about file names, directly through the nsuserdefaults operation, the default is stored in the preferences.
• Direct access to software preferences via Nsuserdefaults (library/preferences)
3> How do I use preference settings for storage? Setobject:forkey storage is called with Nsuserdefaults.
• Preference setting the underlying implementation principle: the bottom is actually using a dictionary to store some key-value pairs.
• Preferences Benefits: can quickly store some key-value pairs, if you use a dictionary to store, also need to get the file name is more troublesome.
• Disadvantage of Preferences: cannot be stored in time, need to do synchronous operation, the data in memory synchronized to the hard disk.
4> How to use preferences to read? Like a dictionary, read from a key just stored.

14> Custom Object Archiving (archive: Data storage)
1> How the custom object is archived: With Nskeyedarchiver, call Archiverootobject:tofile: method, you need to pass an object, customize an object, pass in.
• An error will be reported that the object does not have a Encodewithcoder method, stating that the method is called by default when archiving, to implement this method.
• Encodewithcoder is not allowed by default and must comply with the Nscoding protocol to implement this method.
Encodewithcoder When to call: Object Archive when called
Encodewithcoder function: Tell the System object which attributes need to be archived, how to archive, according to a key to archive, the purpose is to take later, also according to this key to fetch data.
2> How the custom object is unpacked: With Nskeyedunarchiver, call the Unarchiveobjectwithfile method, you need to pass a file name.
• An error will be reported, saying that the object does not have a Initwithcoder method, stating that the default will call this method, to implement this method.
Initwithcoder When to call: Object when the file is being unpacked
Initwithcoder function: Tell the System object which attributes need to be solved, how to solve the file, according to the previously stored key to solve the file
Initwithcoder is an initialization method that needs to initialize the parent class, but cannot invoke [super Initwithcoder:] because the parent class NSObject does not comply with the Nscoding protocol.
3> Initwithcoder when to call [Super Initwithcoder:]
Initwithcoder principle: As long as the parsing of the file will be called, Xib,storyboard are files, so as long as the resolution of the two files, will call Initwithcoder.
• So if you use custom view in storyboard, override the Initwithcoder method, be sure to call [Super Initwithcoder:], because only the system knows how to parse storyboard, if not called, This file cannot be parsed.

iOS Development--ui Advanced (11) application sandbox, archive, files, preferences, plist storage, NSData, custom object archive files

Related Article

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.