Data storage Nsuserdefault Nskeyedarchiver (archive and reverse archive) in iOS

Source: Internet
Author: User

Application Sandbox:

Each iOS app has its own app sandbox (the app sandbox is the file system directory) that is isolated from other file systems. The app must stay in its own sandbox, and other apps won't be able to access it.

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

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

Or: /users/user name/repository/application support/iphone simulator/6.1/applications

Attention:

By default, the emulator directory is hidden, and to display it, you need to enter the following command on the Mac Terminal:

command to display Mac hidden files: Defaults write Com.apple.finder appleshowallfiles YES

command to hide Mac hidden files: Defaults write Com.apple.finder appleshowallfiles NO

application sandbox structure analysis

Documents:

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

Temp:

Save the temporary data that is required to run the app, and then delete the file from that directory when it is finished. When the app is not running, the system may also purge files in that directory. itunes syncs the device without backing up the directory.

library/caches:

Saves data that needs to be persisted when the app runs, and itunes syncs the device without backing up the directory. General storage volume, non-critical data that does not need to be backed up.

library/preference:

Save all of your app's preferences, and the iOS setting app will find the app's settings in that directory. The directory is backed up when itunes synchronizes the device.

Nsuserdefaults

Nsuserdefaults is suitable for storing lightweight local data, such as the data to save a login interface, user name, password, and so on, individuals feel that using nsuserdefaults is preferred. The next time you log in, you can read the last login information directly from the Nsuserdefaults.

Because if you use the Plist file you created, you also have to display the creation of files, read files, very troublesome, but with nsuserdefaults do not care about these things, like reading a string, directly read it.

The data formats supported by Nsuserdefaults are: NSNumber (Integer, Float, Double), Nsstring,nsdate,nsarray,nsdictionary,bool type. It's practical.

Nsuserdefaults is very convenient and easy to read. Here is an example to see how to use: (PS: More details can also refer to the official document HA)

1. Create 2 buttons in storyboard a Save Data button another is to read the data button and associate to Viewcontroller

-(Ibaction) SaveData: (UIButton *) Sender {//Get Nsuserdefaults Object Nsuserdefaults *        Defaults =[nsuserdefaults standarduserdefaults];    Save the data (if no synchronization occurs after setting the data, the data is automatically saved to the Preferences folder at a later point in time) [Defaults setobject:@ "John Doe" forkey:@ "name"];    [Defaults setobject:@ "Wangbinbin" forkey:@ "name"];    [Defaults setinteger:23 forkey:@ "age"];    [Defaults setdouble:1.73f forkey:@ "height"];            [Defaults setobject:@ "Man" forkey:@ "gender"];        synchronizing data [defaults synchronize]; }-(ibaction) ReadData: (UIButton *) Sender {//1. Get Nsuserdefaults Object Nsuserdefaults * Defaults=[nsuserdefaults stand        Arduserdefaults];    Read save data NSString * Name =[defaults objectforkey:@ "name"];    Nsinteger age=[defaults integerforkey:@ "age"];    Double heigth=[defaults doubleforkey:@ "height"];        NSString * gender= [Defaults objectforkey:@ "gender"]; Print Data NSLog (@ "name=%@,age=%lu,height=%f,gender=%@", Name,age,heigth,gender);} 

Nskeyedarchiver

if the object is NSString, Nsdictionary, Nsarray, NSData, NSNumber and other types, it can be used directly:Nskeyedarchiver for archiving and recovery.

Not all objects can be archived directly in this way, only objects that adhere to the Nscoding protocol.

There are 2 ways to nscoding a protocol:

Encodewithcoder:

This method is called every time an object is archived. This method is typically used to specify how to archive each instance variable in an object. You can use: Encodeobject:forkey: method to archive instance variables.

Initwithcoder:

This method is called every time the object is recovered (decoded) from the file. This method typically specifies 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.

Possession.h file @interface possession:nsobject<nscoding> @property (nonatomic,copy) nsstring *name; @property ( nonatomic,assign) Nsinteger age; @property (nonatomic,assign) float height; @end//possession.m File//Encode Property-(void)    Encodewithcoder: (Nscoder *) acoder{[acoder encodeObject:self.name forkey:@ "name"];    [Acoder encodeInteger:self.age forkey:@ "age"];    [Acoder encodeFloat:self.height forkey:@ "height"];    }//Anti-coding-(ID) Initwithcoder: (Nscoder *) adecoder{self.name=[adecoder decodeobjectforkey:@ "name"];    Self.age=[adecoder decodeintegerforkey:@ "age"];    Self.height=[adecoder decodefloatforkey:@ "height"]; return self;} VIEWCONTROLLER.M File//Gets the sandbox Documents folder path NSString *documents =nssearchpathfordirectoriesindomains (    NSDocumentDirectory, Nsuserdomainmask, YES). Lastobject;  NSString * documentpath =[documents stringbyappendingpathcomponent:@ "Documentpath.person"];    Archive possession * person =[[possession alloc]init]; Person.name [email protected] "Wangbin";   person.age=22;    person.height=178.9;            [Nskeyedarchiver Archiverootobject:person Tofile:documentpath];    Anti-archive possession *person1 =[nskeyedunarchiver Unarchiveobjectwithfile:documentpath];    NSLog (@ "name=%@,age=%lu,height=%.2f", person1.name,person1.age,person1.height); NSLog (@ "%@", documentpath);

Note for nskeyedarchiver-archived objects

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

1> should add a sentence [super Encodewithcode:encode] to the Uencodewithcoder: method; Ensure that inherited instance variables can also be encoded, which can also be archived.

2> should add a self = [Super Initwithcoder:decoder] in the Initwithcoder: method; Ensure that inherited instance variables can also be decoded, which can also be restored.

Data storage Nsuserdefault Nskeyedarchiver (archive and reverse archive) in iOS

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.