Explain IOS four ways to save data _ios

Source: Internet
Author: User
Tags sqlite sqlite database

In the iOS development process, no matter what application, will encounter the problem of data preservation. Save the data to the local, can let the program run smoother, do not appear the disgusting chrysanthemum shape, make the user experience better. Here's how to save your data:

1.NSKeyedArchiver: save data in the form of an archive, the data object needs to comply with the Nscoding protocol, and the corresponding class of the object must provide Encodewithcoder: and Initwithcoder: Method. The previous method tells the system how to encode an object, and the latter method tells the system how to decode the object. For example, the possession object archive is saved.

Define possession:

@interface possession:nsobject<nscoding>{//comply with nscoding protocol

    nsstring *name;//to archive type


}

@ Implementation possession

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

      [Acoder encodeobject:name-forKey:@] Name "];


}
-(void) Initwithcoder: (Nscoder *) adecoder{

      name=[[adecoder decodeobjectforkey:@ "name"] retain];

Archive operations:

If you save the possession object Allpossession archive, you need only Nscoder Nskeyedarchiver method Archiverootobject:tofile: You can.

NSString *path = [self possessionarchivepath];

[Nskeyedarchiver archiverootobject:allpossessions Tofile:path]

Decompression operation:

The same method that calls the Nscoder subclass Nskeyedarchiver Unarchiverootobject:tofile: You can

Allpossessions = [[Nskeyedunarchiver Unarchiveobjectwithfile:path] retain];

Disadvantages: Archived form to save data, only one-time archive save and one-time decompression. So you can only target small amounts of data, and it's clumsy to manipulate data, that is, if you want to change a small part of the data, you 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 the boot is turned 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 =[nsuserdefaults standarduserdefaults];
 NSString *name =@ "Default string";
 [Defaults setobject:firstname forkey:@ "name"];
  Obtain UIImage instance

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

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

 [Defaults synchronize];// Persisting data to Standarduserdefaults database with synchronize method

Read data:

Nsuserdefaults *defaults =[nsuserdefaults standarduserdefaults];
 NSString *name = [defaults objectforkey:@ ' name '];//take out the name NSData based on the key value *imagedata
 = [Defaults dataforkey:@ "image"];
 uiimage *image = [uiimage imagewithdata:imagedata];//nsdata conversion to UIImage

3. Write write mode: permanently saved on disk. The specific methods are:

Step one: Get the path where the file will be saved:

Nsarray *documentpaths = Nssearchpathfordirectoriesindomains (nsdocumentdirectory, NSUserDomainMask,YES); Use the C function nssearchpathfordirectoriesindomains to get the full path to the directory in the sandbox. The function has three parameters, the directory type, the He domain mask, and the Boolean value. Where the Boolean value represents the need to extend the path by ~. And the first parameter is invariant, that is nssearchpathdirectory. The latter two parameters are unchanged in iOS, which is: Nsuserdomainmask and YES.
nsstring *ourdocumentpath =[documentpaths objectatindex:0];

Another approach is to use the Nshomedirectory function to get the sandbox path. The specific usage is:

NSString *sandboxpath = Nshomedirectory ();
 Once you have the full sandbox path, you can create a path from it, but you cannot write a file on sandbox's this file layer nor create a directory, but instead create a new writable directory on this basis, such as D Ocuments,library or temp.
nsstring *documentpath = [Sandboxpath
       stringbyappendingpathcomponent:@ "Documents"];// The documents added to the sandbox path, the specific reasons for the previous analysis!

The difference between the two is that it is safer to use nssearchpathfordirectoriesindomains than to add a document behind the nshomedirectory. Because the file directory may change on a system that will be sent in the future.

Step two: Generate files under this path:

NSString *filename=[documentdirectory Stringbyappendingpathcomponent:filename];//filename is the file name to save

Step three: Write data to the file:

[Data writetofile:filename atomically:yes];//writes NSData type Object data to a file named filename

Finally: Read the data from the file:

NSData data=[nsdata datawithcontentsoffile: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 use of iOS, the previous three ways to save compared to relatively more complex. It's still a step by step!

The first step: you need to add SQLite related libraries and headers: under Build phases of the project file, locate the link Binary library (ies), Add Libsqlite3.0.dylib (Libsqlite3.dylib and the former is not known, the two should be similar); Add a header file to a header or source file in a 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 have been more familiar with it! 
//Open Database
if (Sqlite3_open ([Databasefilepath utf8string], &database) ==sqlite_ok) { 
     NSLog (@) SQLITE Dadabase is opened. ");
 else{return; Turn back if it doesn't succeed

On the premise of opening the database, if the database does not have a table, then 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), and/or empty the error string every time you use it, provided to the next use

After the table has been built, the record is inserted:

const char *insertsql= "INSERT into the 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), and/or empty the error string at the end of each use, provided to the next use
} 

Next, query the record:

const char *selectsql= "select Id,name from"; 
 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:

 
 

Note: Write to the database, the string can be char, and the char type is removed from the database, and garbled characters appear when the char type has a medium character. This is because the database uses ASCII encoding by default. So to get the Chinese out of the database correctly, you need to use NSString to receive a string from the database.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.