Four ways to store your data in IOS

Source: Internet
Author: User
Tags sqlite database

Four ways to store your data in IOS

In the process of iOS development, no matter what the application, you will encounter the problem of data preservation. Saving the data locally allows the program to run more smoothly, making the user experience even better. Here's how to save data:

1.NSKeyedArchiver: Save the data in the form of an archive that requires adherence to the Nscoding protocol, and that the class corresponding to the object must provide Encodewithcoder: and Initwithcoder: Methods. Before? A method tells the system how to encode an object, and then a method tells the system how to decode the object. For example, save the Possession object archive.

Define possession:
@interfacePossession: nsobject{//compliance with nscoding Agreement

NSString *name; Pending archive Type

}

@implementation Possession

-(void) Encodewithcoder: (Nscoder *) acoder{

[acoderencodeobject:nameforkey:@ "name"]; }

-(void) Initwithcoder: (Nscoder *) adecoder{
Name=[[adecoder decodeobjectforkey:@ "name"] retain];

}

Archive operation: If you save the possession object Allpossession archive, you only need to nscoder the method Archiverootobject:tofile of the subclass Nskeyedarchiver: Yes.

NSString *path =[selfpossessionarchivepath];
[Nskeyedarchiver archiverootobject:allpossessions Tofile:path]

Decompression operation: Also call Nscoder subclass Nskeyedarchiver Method Unarchiverootobject:tofile: Can allpossessions =[[ Nskeyedunarchiverunarchiveobjectwithfile:path] retain];

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.

2.NSUserDefaults: Used to save application settings and properties, user-saved data. The data still exists after the user opens the program again or after powering it on. 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=[nsuserdefaultsstandarduserdefaults];

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];// Persisting data to the Standarduserdefaults database using the Synchronize method

Read Data :

Nsuserdefaults *defaults=[nsuserdefaultsstandarduserdefaults];
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. Write writes: Permanently saved on disk. The specific methods are:
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];

And what? One way is to use the Nshomedirectory function to get the path of the sandbox. The specific usage is:

NSString *sandboxpath = Nshomedirectory ();
Once you had the Fullsandbox path, can create a path from it, but could not write files on the sandbox of this file layer can not create directories, but should be created on this basis? A new writable directory, such as D Ocuments,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:filename options:0 error:null];//read out data from FileName

4. SQLite: 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 relatively complex? Or is it a step-by-step! or with a third-party Fmdb database to implement, detailed Fmdb usage go to http://blog.csdn.net/eduora_meimei/article/details/44061771

Step one: Need to add SQLite related libraries and header files: Under the buildphases of the project file, locate the link Binary library (ies) and add libsqlite3.0.dylib ( The difference between the Libsqlite3.dylib and the former is not known, 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:

Note Before use: If you do not add any tables to the database, this database is not established, does not generate any files on the hard disk, and if the database already exists, the database will open.

Nsarray*documentspaths=nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask, YES);
NSString *databasefilepath=[[documentspathsobjectatindex: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 dadabaseisopened.");}

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 keyautoincrement,name text)"; if (sqlite3_exec (database, Createsql, Null,null,&error) ==SQLITE_OK) {

NSLog (@ "CREATE TABLE is OK.");

else {

Sqlite3_free (error);//Empty the error string after each use, provided to the next? Use}

After the build table is complete, insert the record:

const char *insertsql= "Insert Intoaperson (name) VALUES (' GG ')";
if (sqlite3_exec (database, insertsql, NULL, NULL, &ERROR) ==SQLITE_OK) {

NSLog (@ "insert operation isOK.");

else {

NSLog (@ "error:%s", error);

NSLog (@ "error:%s", error);

Sqlite3_free (error);//Empty the error string after each use, provided to the next? Use}

Next step, query the record:

const char *selectsql= "selectid,namefrom a person";
Sqlite3_stmt *statement;
if (SQLITE3_PREPARE_V2 (Database,selectsql,-1, &statement,nil) ==SQLITE_OK) {

NSLog (@ "Select operation isOK.");

else {

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.

Four ways to store your data 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.