Several common ways to store iOS data

Source: Internet
Author: User

1, Nskeyarchiver

2, Nsuserdefault

3, PList

4. Write

5, SQLite

6, KeyChain

Example:

1, Nskeyarchiver

To deposit data into a file:

NSString *rootdir =nshomedirectory (); NSString*path = [RootDir stringbyappendingpathcomponent:@"Test.txt"]; Nsmutabledata*data =[nsmutable data]; Nskeyedarchiver*archiver =[[Nskeyedarchiver alloc] initforwritingmutabledata:data]; Nsarray*array = @[@" One",@" Both"]; [Archiver encodeint: -Forkey:@" Age"];//equivalent to Sharedpreference putinteger (key,value);[Archiver Encodeobject:array Forkey:@"names"];//[Archiver finishencoding];//This method is called, the data is stored[archiver release];if([Data Writetofile:path Atomically:yes]) {NSLog (@"object saved to file successfully");}

To remove data from a file:

 nsdata *data = [NSData Datawithcontentoffile:path]; Nskeyedarchiver  *unarchiver =[[nskeyedarchiver Alloc] Initforreadingwithdata: Data];  int  age = [unarchiver decodeintforkey:@ " age  ]; //  remove value  Nsarray *array = [unarchiver decodeobjectforkey:@ " names   "  

2, Nsuserdefault: used to save the application settings and properties, the 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.

    //1. Deposit DataNsarray *array = @[@"ABC",@"D"]; Nsuserdefaults*userdefault =[Nsuserdefaults Standarduserdefaults]; [Userdefault Setinteger:123Forkey:@" Number"]; [Userdefault setobject:array Forkey:@"Array"]; [Userdefault synchronize];//Deposit File//2. Remove the dataNsinteger number = [Userdefault integerforkey:@" Number"]; Nsarray*array = [Userdefault objectforkey:@"Array"];

3. PList: Store simple basic data types

4. Write:

The first step: Get the path where the file will be saved.

1 nsarray *documentpaths = nssearchpathfordirectoriesindomains (nsdocumentdirectory,  Nsuserdomainmask,yes); 2 nsstring *ourdocumentpath =[documentpaths objectatindex:0]; 3 4 // 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 the path needs to be extended through the ~.
And the first parameter is constant, which is nssearchpathdirectory. In iOS, the latter two parameters are the same: Nsuserdomainmask and YES.

Or use the Nshomedirectory method to get the sandbox path.

NSString *sandboxpath =*documentpath = [Sandboxpath stringbyappendingpathcomponent:@ " Documents " ]; // add documents to the sandbox path

the difference between the two is: using Nssearchpathfordirectoriesindomains is more secure than adding document after Nshomedirectory. Because the file directory may change on future systems that are sent.

Step two: Generate files under this path:

NSString *filename=[documentdirectory stringbyappendingpathcomponent:savefilename]; // Savefilename is the file name of the saved files

Step three: Write the data

[Data writetofile:savefilename atomically:yes]; // writes the NSData type Object data to the file with the file name Savefilename

Fourth step: Read the data from the file

NSData data=[nsdata datawithcontentsoffile:savefilename Options:0  error:null]; // Read and remove data from the Savefilename

5, SQLite

The 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) 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: Use SQLite:

Nsarray *documentspaths=*databasefilepath=[[documentspaths objectatindex:0] stringByAppendingPathComponent:@ "mydb"];
Open Database

if (Sqlite3_open ([Databasefilepath utf8string], &database) ==SQLITE_OK)

{
NSLog (@ "SQLite dadabase is opened.");
}
else{

Return

}//Open does not succeed on return

//if the database does not have a table, start building the table
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
{
      nslog (@ "error:%s", error);
      sqlite3_free (Error); //empty the error string each time it is used, given to the next use of the
} 

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); //each use clears the error string for the next use
}

Query record:

const char *selectsql= "selectid,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 iOS data

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.