Introduction to iOS Common storage methods

Source: Internet
Author: User
Tags tmp folder

in the iOS app development process, you often need to manipulate data that requires persistent retention, such as user-related settings for the app, data that needs to be cached locally, and so on. This paper makes a tidy-up of the storage methods used frequently in OC.

Common Storage Tools/methods:

Nsuserdefaults class

plist file

Solution Archive

Storing the sandbox manually

Sqlite

CoreData

Third-party data storage framework

1. Nsuserdefaults

Generally for some basic user settings, because the amount of data is small, we can use the Nsuserdefaults class in the OC language for processing. The way to use it is simple, just call the methods in the class:

Nsmutablearray *mutarr = [[Nsmutablearray alloc]initwithobjects:@ "1", nil];

Storing and synchronizing the array

[[Nsuserdefaults Standarduserdefaults] Setobject:mutarr forkey:@ "Mutablearr"];

[[Nsuserdefaults standarduserdefaults] synchronize];

Read the stored array print

Nsarray *arr = [[Nsuserdefaults standarduserdefaults] objectforkey:@ "Mutablearr"];

NSLog (@ "%@", arr);

In addition to storing arrays, dictionaries, and NSData, the Nsuserdefaults class can also store OC base type properties directly. However, you cannot directly act on a custom object, and if it is a custom object that needs to be archived, it will be mentioned later.

2. plist file

The plist file is a resource bundle for Xcode and can also be used as a storage tool.

1. Create the plist file in the project. The benefit of creating in the project is the visualization of the file, we can see the content of the file intuitively, and Xcode also provides the function of directly manipulating the file. It is convenient for us to change the contents of the file and delete. The disadvantage of this approach is that the plist file in the project is generally stored as a solid state data situation, and it is not easy to manipulate the data that needs to be changed frequently.

Get the data code in the file

    NSString *string = [[NSBundle mainbundle] pathforresource:@ "testplist" oftype:@ "plist"];
Nsdictionary *dic = [Nsdictionary dictionarywithcontentsoffile:string];
NSLog (@ "%@", dic); Print the contents of a file

2. Code read/write Plist file. Avoid the hassle of creating plist files in your project that can cause inconvenience to change.

    Create a plist file  testplist    nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask,yes);    NSString *plistpath = [Paths objectatindex:0];    NSLog (@ "path =%@", plistpath);    NSString *filename=[plistpath stringbyappendingpathcomponent:@ "Testplist.plist"];    nsfilemanager* fm = [Nsfilemanager Defaultmanager];    [FM createfileatpath:filename Contents:nil Attributes:nil];        Write content    nsdictionary *dic = [nsdictionary dictionarywithobjectsandkeys:@ "test", nil];    [DiC Writetofile:filename Atomically:yes];        Read file    nsdictionary* dic2 = [Nsdictionary dictionarywithcontentsoffile:filename];    NSLog (@ "dic is:%@", Dic2);

3. Solution Archive

Previously, neither Nsuserdefaults nor plist can store custom objects, and OC provides an understanding of the archive to solve the problem. The solution archive is for an object, assuming we now have a Testmodel class that needs to be archived and picked up on the code.

object's. h file

#import <Foundation/Foundation.h> @interface testmodel:nsobject <NSCoding>    //archiving is subject to the Nscoding protocol, and implement related methods @property (Nonatomic,strong) nsstring *name; @property (nonatomic,assign) Nsinteger age; @property (nonatomic, Strong) NSString *sex; @end

object's. m file

#import "TestModel.h" #define NAME @ "name" #define Age  @ ' age ' #define SEX  @ "Sex" @implementation Testmodel
Two ways to implement the Protocol in Nscoding-(ID) Initwithcoder: (Nscoder *) adecoder{ if (self = = [Super init]) { self.name = [ Adecoder Decodeobjectforkey:name]; Self.sex = [Adecoder decodeobjectforkey:sex]; Self.age = [[Adecoder decodeobjectforkey:age] integervalue]; } return self;} -(void) Encodewithcoder: (Nscoder *) acoder{ [Acoder encodeObject:self.name forkey:name]; [Acoder encodeObject:self.sex forkey:sex]; [Acoder Encodeobject:[nsnumber numberWithInteger:self.age] forkey:age];} -(NSString *) description{ return [NSString stringwithformat:@ "%@--%@--%ld years", Self.name,self.sex, (long) Self.age];} @end

Next, the Testmodel class can be archived using the solution/Archive helper class.

    Create an object and assign a value testmodel *model = [[Testmodel alloc]init];    Model.name = @ "Xiao Ming";    Model.age = 25;         Model.sex = @ "man";    Archive Nsmutabledata *data = [[Nsmutabledata alloc] init];    Create an Archive helper class nskeyedarchiver *archiver = [[Nskeyedarchiver alloc] initforwritingwithmutabledata:data];    coding [Archiver Encodeobject:model forkey:@ "model"];    End code [archiver finishencoding];    Write to sandbox nsarray *array = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);    NSString *filename = [Array.firstobject stringbyappendingpathcomponent:@ "Archivermodel"];    if ([Data writetofile:filename Atomically:yes]) {NSLog (@ "Archive succeeded");    }//Solution NSData *undata = [[NSData alloc] initwithcontentsoffile:filename];    Solution Auxiliary class Nskeyedunarchiver *unarchiver = [[Nskeyedunarchiver alloc] initforreadingwithdata:undata];    Decode and unpack the model Testmodel *unmodel = [unarchiver decodeobjectforkey:@ "model"];    NSLog (@ "%@", Unmodel); Close the solution [UnarchiVer finishdecoding]; 

Print after running code

4. Manually store the sandbox

The iphone sandbox model has four folders, namely Documents,tmp,app,library.
1. Documents directory: You should write all the application data files to this directory. This directory is used to store user data or other information that should be backed up regularly. In order not to make the backup of the app too large, we do not recommend storing large volumes of files here.
2. Appname.app directory: This is the application's package directory, which contains the application itself. Because the application must be signed, you cannot modify the contents of this directory at run time, which may cause the application to fail to start.
3. Library directory: There are two sub-directories under this directory: Caches and Preferences
Preferences directory: Contains the application's preferences file. Instead of creating a preference file directly, you should use the Nsuserdefaults class to get and set your application's preferences.
Caches directory: Used to hold application-specific support files, saving the information that is needed during application startup. If you're careful, you'll find that almost all of the third-party framework's cache information is in this file, and the general bulk file is here.
4. tmp directory: This directory is used to store temporary files, saving information that is not needed during the application restart. Nsuserdefaults saved files are usually in the TMP folder.
Ways to get these directory paths:
1, get the Home directory path function:

NSString *homedir = Nshomedirectory ();

2. Method for obtaining the Documents directory path:

Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES); NSString *docdir = [Paths objectatindex:0];

3, get the Caches directory path method:

Nsarray *paths = Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES); NSString *cachesdir = [Paths objectatindex:0];

4. Method to get the TMP directory path:

Only the basic data in OC can be saved in the sandbox, and the custom objects cannot be stored directly. The deposit method is as follows.

    1, Get home directory path function://    NSString *homedir = Nshomedirectory ();//    2, get the Documents directory path method://    Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);//    NSString *docDir = [Paths objectatindex:0];//    3, get the Caches directory path method:    Nsarray *paths = Nssearchpathfordirectoriesindomains ( Nscachesdirectory, Nsuserdomainmask, YES);    NSString *cachesdir = [Paths objectatindex:0];//    4, the method to get the TMP directory path://    NSString *tmpdir = Nstemporarydirectory ();        //Suppose we need to save data to the cache and name it in    the TXT format file named Test NSString *filepath = [Cachesdir stringbyappendingpathcomponent:@ "test.txt"];    Nsarray *dic = [[Nsarray alloc] initwithobjects:@ "test" @ "Test1", nil];        if ([dic writetofile:filepath Atomically:yes]) {        NSLog (@ "deposit success");    }    Remove data Print    NSLog (@ "%@", [Nsarray Arraywithcontentsoffile:filepath]);

Print

Introduction to iOS Common storage methods

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.