Several common ways to store data in iOS

Source: Internet
Author: User
Tags list of attributes sqlite database

Myself a little summed up the next, convenient for everyone to view

1. Write writes directly to the file method

Permanently saved on disk, the objects that can be stored are nsstring, Nsarray, Nsdictionary, NSData, NSNumber, and the data is all stored in a property list file (*.plist file).

The concrete steps are as follows:
Step one: Get the path that the file is about to save:
Nsarray*documentpaths=nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes);// Use the C function nssearchpathfordirectoriesindomains to get the full path of the directory in the sandbox. The function has three parameters, a directory type, a he domain mask, and a Boolean value. Where the Boolean value indicates whether you need to extend the path through the? ~. And the first parameter is constant, which is nssearchpathdirectory. In iOS, the latter two parameters are the same: Nsuserdomainmask and yes.
NSString *ourdocumentpath =[documentpaths objectatindex:0];
Another way is to use the Nshomedirectory function to get the sandbox path. The specific usage is:
NSString *sandboxpath = Nshomedirectory ();
Once you are having the Fullsandbox path, you can create a path from it, but you cannot write a file on the layer of this file on the sandbox or create a directory, but this should be based on creating a new writable directory, such as do Cuments,library or temp. NSString *documentpath = [Sandboxpath
stringbyappendingpathcomponent:@ "Documents"];//to add documents to the sandbox path, the specific reason before the analysis!
The difference between the two is that using Nssearchpathfordirectoriesindomains is more secure than adding a document behind Nshomedirectory. Because the file directory may change on future systems that are sent.
Step two: Generate files under this path:
NSString*filename=[documentdirectorystringbyappendingpathcomponent:filename];//filename is the file name of the saved files
Step Three: Write data to the file:
[datawritetofile:filenameatomically:yes];//writes NSData type Object data to a file named filename
finally: Read the data from the file:
Nsdatadata=[nsdatadatawithcontentsoffile:filenameoptions:0 error:null];//read out data from filename

2. Nsuserdefault method

Used to store application settings information, the file is placed in the Library/perference directory, nsuserdefaults the configuration information in the form of a dictionary, support dictionary items include: string or array, in addition to support the basic format such as numbers. A nutshell is: A dictionary of basic types of small data. The method of operation is almost identical to that of the nsdictionary, and the return value of the specified type can be obtained by specifying a method of the return type. The types of data that Nsuserdefaults can store include: NSData, NSString, NSNumber, NSDate, Nsarray, Nsdictionary. If you want to store other types, you need to convert to the previous type to use Nsuserdefaults storage. The specific implementation is:

Save data:

Nsuserdefaults *defaults =[nsuserdefaults Standarduserdefaults];
NSString *name [email protected] "default string";
[Defaults setobject:firstname forkey:@ "name"];
Get UIImage instances

UIImage *image=[[uiimage alloc]initwithcontentsoffile:@ "Photo.jpg"];

NSData *imagedata = uiimagejpegrepresentation (image),//uiimage object converted to NSData

[Defaults synchronize];//uses synchronize method to persist data to the Standarduserdefaults database

Read Data :

Nsuserdefaults *defaults =[nsuserdefaults Standarduserdefaults];
NSString *name = [Defaults objectforkey:@ "name"];//Remove name based on key value
NSData *imagedata = [Defaults dataforkey:@ "image"];
UIImage *image = [UIImage imagewithdata:imagedata];//nsdata converted to UIImage

3. Archive method

In contrast to the list of attributes, as a durable scheme for lightweight storage, data archiving is encrypted, and data is converted to binary data as it is archived, so security is much higher than the list of attributes. In addition to using archiving, we can write complex objects to a file, and the same way that objects are written to disk, regardless of how many objects are added.

Use Nskeyedarchiver to serialize the custom data and save it in the sandbox directory. The premise of using this archive is to have the stored data model comply with the Nscoding protocol and implement its two protocol methods. (Of course, if the nssecurecoding protocol can be adhered to for more secure storage, this is the new feature after IOS6)

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:

First, create a class that inherits NSObject, which adheres to the Nscoding protocol

TestPerson.h

@interface testperson:nsobject<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)

This method is called when an archive operation is made

In this method, 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 this method, write clearly which properties of the object to extract

-(ID) Initwithcoder: (Nscoder *) Adecoder

{

NSLog (@ "called the Initwithcoder 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

Here's a tip: Use the static modifier instead of the macro definition. In the above serialization, we can see that the Nscoding protocol method serializes the data and uses a key to save it. Under normal circumstances we can use macros to define keys, but too many macro definitions will cause a lot of loss at compile time. You can override the macro definition by defining a static variable using static.

Static NSString * Const KUSERNAMEKEY = @ "UserName";

With custom data following the Nscoding protocol, we can use Nskeyedarchiver and nskeyedunarchiver to access persisted data:

-(Ibaction) SaveData: (ID) sender

{

Create an instance of a custom class

_p = [[Testperson alloc]init];

_p.name = @ "Lotheve";

_p.age = 20;

_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");

}

Cons: Archive the form to save data, only one-time archive save and one-time decompression. So only a small amount of data, and the data operation is clumsy, that is, if you want to change a small part of the data, still need to extract the entire data or archive the entire data.

4. SQLite method (FMDB)

Use SQLite database to store data. SQLite as a small and medium-sized database, the application of iOS, in front of three ways to save compared to a relatively more complex. It's a step-by-step!

First step: You need to add SQLite related libraries and header files: Under Build phases of the project file, locate the link Binary library (ies), Add Libsqlite3.0.dylib (the difference between Libsqlite3.dylib and the former does not know, the two should be similar); Add a header file to the header file or source file in the project file #import "/usr/include/sqlite3.h"

Step two: Start using SQLite:

Nsarray *documentspaths=nssearchpathfordirectoriesindomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *databasefilepath=[[documentspaths objectatindex:0] stringbyappendingpathcomponent:@ "MyDB"];
The above two sentences are already more familiar with it!
Open Database
if (Sqlite3_open ([Databasefilepath utf8string], &database) ==SQLITE_OK) {
NSLog (@ "SQLite dadabase is opened.");
}
else{return;} Turn on unsuccessful to return

When the database is open, if the database does not have a table, then you start to build the table Oh!
Char *error;
const char *createsql= "CREATE TABLE (ID integer primary key autoincrement, name text)";
if (sqlite3_exec (database, createsql, NULL, NULL, &ERROR) ==SQLITE_OK) {
NSLog (@ "CREATE TABLE is OK.");
}
Else
{
NSLog (@ "error:%s", error);
Sqlite3_free (error);//Empty the error string each time it is used, provided to the next use
}

After the build table is complete, insert the record:

const char *insertsql= "INSERT into a person (name) VALUES (' GG ')";
if (sqlite3_exec (database, insertsql, NULL, NULL, &ERROR) ==SQLITE_OK) {
NSLog (@ "insert operation is OK.");
}
Else
{
NSLog (@ "error:%s", error);
Sqlite3_free (error);//Empty the error string each time it is used, provided to the next use
}

Next, query the record:

const char *selectsql= "Select id,name from a person";
Sqlite3_stmt *statement;
if (SQLITE3_PREPARE_V2 (Database,selectsql,-1, &statement, nil) ==SQLITE_OK) {
NSLog (@ "Select operation is OK.");
}
Else
{
NSLog (@ "error:%s", error);
Sqlite3_free (Error);
}
while (Sqlite3_step (statement) ==sqlite_row) {
int _id=sqlite3_column_int (statement, 0);
NSString *name= (char*) sqlite3_column_text (statement, 1);
NSLog (@ "Row>>id%i, Name%s", _id,name);
}
Sqlite3_finalize (statement);

Finally, close the database:

Sqlite3_close (database);

Note: To write to a database, the string can be char, and the char type is removed from the database and garbled when the char type has a representation of the Chinese characters. This is because the database uses ASCII encoding by default. Therefore, in order to correctly remove the Chinese from the database, we need to use NSString to receive the string extracted from the database.

Several common ways to store data in iOS

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.