IOS four ways to save data

Source: Internet
Author: User
Tags sqlite database

Original address: http://blog.sina.com.cn/s/blog_7453d50f0101ickz.html

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 without the appearance of an obnoxious chrysanthemum shape, 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:
@interface possession:nsobject{

Compliance with Nscoding Protocol

NSString *name;//Pending Archive type

}

@implementation Possession

-(void) Encodewithcoder: (Nscoder *) Acoder

{

[Acoder encodeobject:name forkey:@ "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 = [self possessionarchivepath];
[Nskeyedarchiver archiverootobject:allpossessions Tofile:path]
Decompression operation: Also call the method of Nscoder subclass Nskeyedarchiver Unarchiverootobject:tofile: Can allpossessions = [[Nskeyedunarchiver Unarchiveobjectwithfile: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 =[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];// Persisting data to the Standarduserdefaults database using the Synchronize method

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. 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 C function nssearchpathfordirectoriesindomains to get the full path of the directory in the sandbox

Diameter. 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 has the full sandbox path, can create a path from it, but can 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, example such as Documents,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=[documentdirectory Stringbyappendingpathcomponent:filename];//filename is the filename of the saved file

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 application of iOS, in front of three ways to save compared to relatively complex? Or is it? Step by Step!

Step one: Need to add SQLite related libraries and header files: Under Build phases 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=[[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 {

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

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= "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 {

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.

IOS four ways to save data

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.