iOS Development-data storage (direct write, Nsuserdefaults, nskeyedarchiver)

Source: Internet
Author: User
Tags tmp folder uikit

Data storage (direct write, Nsuserdefaults, nskeyedarchiver)
the common ways to access files in iOS are:

1, directly write the way of the file, you can store the object has NSString, Nsarray, Nsdictionary, NSData, NSNumber, the data are all stored in a property list file (*.plist file).

2, Nsueserdefaults (preferences), used to store application settings information, files placed in the Perference directory.

3, archive operation (Nskeyedarchiver), different from the previous two, it can put the custom object in the file.

First of all, each developer should know that for an application, there is a unique sandbox that corresponds to each application that cannot manipulate files across the sandbox.

First, get the sandbox path and store the data by writing the file

Look directly at the code:

#import "ViewController.h" @interface Viewcontroller () @end @implementationviewcontroller-(void) Viewdidload {[Super    Viewdidload];    Do any additional setup after loading the view,typically from a nib. [Self mainoperation];}    -(void) mainoperation{//Get the Cache folder path in Sandbox//method one//sandbox home directory NSString *homepath = Nshomedirectory ();       Stitching path NSString *path = [HomePath stringbyappendingpathcomponent:@ "library/caches"]; Method two//the first parameter target folder directory (Nscachesdirectory find cache folder), the second parameter is to find the directory of the domain (Nsuserdomainmask to find in the user directory), the third parameter is the result of whether the home directory is expanded, not expanded is displayed as    ~ Nsarray *arr = Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES);    Although the method returns an array, there is only one element in the array because a destination folder has only one directory.    NSString *cachepath = [arr lastobject];  or//NSString *cachepath = [arr objectatindex:0];    /**//Get the document folder in the sandbox or the TMP folder path can use the above two methods//tmp folder path can be directly obtained nsstring *tmppath = Nstemporarydirectory (); NSLog (@ "%@", Tmppath), **///stitching path (target path), this time if the directory does not exist in this lotheve.plist file, this directory is actually not savedIn the.    NSString *filepath = [CachePath stringbyappendingpathcomponent:@ "Tese.plist"];       NSLog (@ "%@", FilePath);    Create data nsdictionary *content = @{@ "Dictionary data Test 1": @ "1", @ "Dictionary data Test 2": @ "2", @ "Dictionary data Test": @ "3"};      Save the data to a file in the destination path (this time if the file does not exist in the path will be created automatically)//write the file with the WriteToFile method will overwrite the original contents [content Writetofile:filepath Atomically:yes];    Read the data (read the contents of the file in a dictionary) nsdictionary *dic = [Nsdictionary Dictionarywithcontentsoffile:filepath]; NSLog (@ "%@", DIC);} @end

lotheve.plist files in the Library/caches directory in the sandbox


File contents:

Second, using Nsueserdefaults (preferences) to achieve data storage

Each app has a nsuesrdefaults instance that can store app configuration information and user information, such as saving user names, passwords, font size, automatic login, and so on. The data is automatically saved in the sandbox's libarary/preferences directory. Similarly, the method can only access data of the NSString, Nsarray, Nsdictionary, NSData, and NSNumber types.

code example:

#import "LXXViewController.h" @interface Lxxviewcontroller () @end @implementationlxxviewcontroller-(void) viewdidload{    [Super Viewdidload];    Self.title = @ "Nsuserdefaults Demo";} Click button to save data-(Ibaction) SaveData: (ID) Sender {    //Get Nsuserdefaults object    nsuserdefaults *userdefaults = [ Nsuserdefaults Standarduserdefaults];    Save data, do not need to set the road, Nsuserdefaults to save the data in the preferences directory    [userdefaults setobject:@ "Lotheve" forkey:@ "name"];    [Userdefaults setobject:@ "Nsuserdefaults" forkey:@ "demo"];    Save (synchronize) the data immediately (if you do not write this, you will automatically save the data in the Preferences directory at some point in the future)    [Userdefaults synchronize];    NSLog (@ "Data Saved");} Click button to read data-(ibaction) GetData: (ID) sender{    //Get Nsuserdefaults object    nsuserdefaults *userdefaults = [ Nsuserdefaults Standarduserdefaults];    Read Data    nsstring *name  = [userdefaults objectforkey:@ "name"];    NSString *demo = [Userdefaults objectforkey:@ "Demo"];    Print Data    NSLog (@ "name =%@ Demo =%@", Name,demo);} @end


Two buttons are set in the Interface building:


After clicking "Save Data", view the Libarary/preferences directory in the sandbox:


The data is written to disk in plist format. Click to view data:


Third, Nskeyedarchiver (archive operation)

The main benefit of storing data using archive operations is that nskeyedarchiver can store custom objects, unlike the previous two methods, which store only a few commonly used data types.

code example:

It is important to note that the object classes that need to be saved must refer to the Nscoding protocol and implement

-(void) Encodewithcoder: (Nscoder *) acoder-(ID) Initwithcoder: (Nscoder *) Adecoder   

1. File structure:


2. code example:

Lxxviewcontroller.m

#import "LXXViewController.h" #import "TestPerson.h" @interface Lxxviewcontroller () @property (nonatomic, Strong) Testperson *p; @end @implementationlxxviewcontroller-(void) viewdidload {    [Super viewdidload];} -(Ibaction) SaveData: (ID) sender{    //Create an instance of a custom class    _p = [[Testperson alloc]init];    _p.name = @ "Lotheve";    _p.age =;    _p.sex = @ "M";    _p.familymumbers = @[@ "Father", @ "Mather", @ "Me"];       Get file path    nsstring *docpath = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) Lastobject];    File types can be arbitrarily taken, not necessarily the correct format    nsstring *targetpath = [DocPath stringbyappendingpathcomponent:@ "Lotheve.plist"];      Save the custom object under the specified path    [nskeyedarchiver archiverootobject:_p Tofile:targetpath];    NSLog (@ "file is stored");}

-(Ibaction) GetData: (ID) sender{    //Get file path    nsstring *docpath = [Nssearchpathfordirectoriesindomains ( NSDocumentDirectory, Nsuserdomainmask, YES) lastobject];    NSString *targetpath = [DocPath stringbyappendingpathcomponent:@ "Lotheve.plist"];       Testperson *person = [Nskeyedunarchiver Unarchiveobjectwithfile:targetpath];    NSLog (@ "name =%@, age =%ld, sex =%@, familymubers =%@", person.name,person.age,person.sex,person.familymumbers);    NSLog (@ "file extracted");} @end


TestPerson.h

#import <UIKit/UIKit.h> @interface testperson:uiviewcontroller<nscoding> @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) Nsinteger age; @property (nonatomic, copy) NSString *sex; @property ( Nonatomic, strong) Nsarray *familymumbers; @end


Testperson.m

 #import "TestPerson.h" @interface Testperson () @end @implementationtestperson-(void) viewdidload{[Super Viewdidload];} #pragma mark-nscoding protocol method (must be implemented)///When the archive operation is called the method//In this method to write clearly which properties of the object to store-(void) Encodewithcoder: (Nscoder *) Acoder    {NSLog (@ "called the Encodewithcoder Method");    [Acoder encodeobject:_name forkey:@ "name"];    [Acoder encodeinteger:_age forkey:@ "age"];    [Acoder encodeobject:_sex forkey:@ "Sex"]; [Acoder encodeobject:_familymumbers forkey:@ "Familymumbers"];}    This method is called when the file is being manipulated//in which the properties of the object to be extracted-(ID) Initwithcoder: (Nscoder *) adecoder{NSLog (@ "called Initwithcoder Method") are written in this method;        if (self = [super init]) {self.name = [adecoder decodeobjectforkey:@ "name"];        Self.age = [Adecoder decodeintegerforkey:@ "age"];        Self.sex = [Adecoder decodeobjectforkey:@ "sex"];    _familymumbers = [Adecoder decodeobjectforkey:@ "Familymumbers"]; } return self;} @end 

After clicking "Save Data", view the documents directory in the sandbox:


Click to view the contents of the file:


Click "Extract Data" to print the results:


iOS Development-data storage (direct write, Nsuserdefaults, nskeyedarchiver)

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.