Simple data storage--plist, Nskeyedarchiver Archive, Nsuserdefaults (preferences), SQLite (embedded database)

Source: Internet
Author: User
Tags sqlite database xml attribute

Five Ways to store data:

1. XML attribute list (plist archive)

2. Nskeyedarchiver Archive (encrypted form)

3. Nsuserdefaults (preference setting)

4. SQLite (embedded database)

5. Core Date (embedded database for object-oriented approach)

I. Reading and writing of plist

Disadvantages:

1. Save in clear text

2, limited Operation object only Nsarray, Nsmutablearray, nsdictionary, nsmutabledictionary support

(as long as the corresponding WriteToFile method is called in the archive, the solution calls Arraywithcontentsoffile or Dictionarywithcontentsoffile)

Write:

1.//Get to the document file path

Nsarray *paths = Nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes);

NSString *path = paths[0];

2.//Create Plist file

NSString *filename = [path stringbyappendingpathcomponent:@ "Test.plist"];

3,//build dictionary or Nsarray write

Nsdictionary *dic1 = @{@ "name": @ "Zhang" @ "age": @22,@ "Sex": @ "Mans"};

Nsdictionary *dic2 = @{@ "name": @ "li" @ "age": @54,@ "Sex": @ "female"};

Nsdictionary *dic3 = @{@ "name": @ "Wang" @ "age": @25,@ "Sex": @ "Mans"};

Nsdictionary *dic = @{@ "Z":d ic1,@ "L":d ic2,@ "W":d IC3};

4.//write to Test.plist

[DiC Writetofile:filename Atomically:yes];

Read:

1.//Get to the document file path

Nsarray *paths = Nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes);

NSString *path = paths[0];

2.//plist file

NSString *filename = [path stringbyappendingpathcomponent:@ "Test.plist"];

3.//Read

Nsdictionary *readdic = [Nsdictionary dictionarywithcontentsoffile:filename];

Nsdictionary *person = readdic[@ "Z"];

NSString *name = person[@ "name"];

Second, Nskeyedarchiver archive (encrypted form)

Divided into simple archives (for individual objects without setting key) and complex object archives (different keys are required for multiple objects)

OS x is: Nsarchiver and Nsunarchiver

IOS: Nskeyedarchiver and Nskeyedunarchiver

1. Simple archiving:

NSString *str = @ "Hello";

What to archive

It can also be nsarray *array = @[@ "A", @ "B", @ "C"];

Nsarray *array = Nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes);

NSString *path = array[0];

NSString *filename = [path stringbyappendingpathcomponent:@ "Test.arc"];

Get path

if (![ Nskeyarchiver Archiverootobject:str Tofile:filename])

{

NSLog (@ "Archiver failed!");

}

Archive

(id) st = [Nskeyedunarchiver unarchiverobjectwithfile:filename];

Solution file

(The above ID refers to an arbitrary object, which can be either nsstring or Nsarray);

2. Complex object Archiving (multi-object archiving)

Archive Address

NSString *filename2 = [path stringbyappendingpathcomponent:@ "Test2.arc"];

Archive:

Setting up data

int myInt = 31;

NSString *mystring = @ "Hello";

NSNumber *mynumber = @32;

Nsarray *myarray = @[@ "OK" @ "no" @ "Byel"];

Nsdictionary *mydic = @{@ "Dic1": @ "a", @ "Dic2": @ "B", @ "DIC3": @ "C"};

New data for temporary storage

Nsmutabledata *data = [[Nsmutabledata alloc]init];

The settings archive is saved in the data object

Nskeyedarchiver *archiver = [[Nskeyedarchiver alloc]initforwritingwithmutabledata:data];

Archive the object and set key to read

[Archiver encodeint:myint forkey:@ "int"];

[Archiver encodeobject:mystring forkey:@ "string"];

[Archiver encodeobject:mynumber forkey:@ "number"];

[Archiver encodeobject:myarray forkey:@ "Array"];

[Archiver encodeobject:mydic forkey:@ "dictionary"];

End Archive

[Archiver finishencoding];

Write file

[Data writetofile:filename2 Atomically:yes];

Read the document:

Defining data

int myInt2;

NSString *mystring2;

NSNumber *mynumber2;

Nsarray *myarray2;

Nsdictionary *mydic2;

Get to file, store in Data2

Nsmutabledata *data2 = [[Nsmutabledata alloc]initwithcontentsoffile:filename2];

Defining the Solution Data2

Nskeyedunarchiver *unarchiver = [[Nskeyedunarchiver alloc]initforreadingwithdata:data2];

Unpack and store in a variable

MyInt2 = [unarchiver decodeintforkey:@ "int"];

MyString2 = [Unarchiver decodeobjectforkey:@ "string"];

MyNumber2 = [Unarchiver decodeobjectforkey:@ "number"];

MyArray2 = [unarchiver decodeobjectforkey:@ "Array"];

MyDic2 = [Unarchiver decodeobjectforkey:@ "dictionary"];

End Solution

[Unarchiver finishdecoding];

Third, Nsuserdefaults

The data types supported by Nsuserdefaults are: NSNumber (Nsinteger, float, double), Nsstring,nsdate,nsarray,nsdictionary,bool.

1. Save data:

Storing NSString objects in Nsuserdefaults

NSString *password = @ "1234567";

Nsuserdefaults *user = [Nsuserdefaults standarduserdefaults];

[User Setobject:password forkey:@ "UserPassword"];

2. Take data

Nsuserdefaults *user = [Nsuserdefaults standarduserdefaults];

NSString *password = [user objectforkey:@ "UserPassword"];

Save custom Data with NSData

Four, SQLite database

Characteristics:

1, in iOS need to use the C language syntax for database operations, access (unable to use OBJC direct access, because the Libsqlite3 framework based on C language)

2, usually do not need to close the connection after establishing the connection (can be manually closed)

Step: (Import libsqlite3 frame first)

1. Open the database.

Opening the database with Sqlite_open () specifies a database file to save the path to, or open if the file exists, otherwise it is created and opened. (Opening the database will give you an object of type sqlite3, which you need to do other things later)

2. Execute the SQL statement.

The Execute SQL statement includes statements with return values and no return value statements.

(1), for the return value of the statement (such as additions and deletions and other operations) directly through the sqlite3_exec () function execution;

(2), for a statement with a return value (such as a query operation) first through SQLITE3_PREPARE_V2 () to perform syntax detection, and then through Sqlite3_step () to take out the query results of each row of data, for each row of data can be through the corresponding Sqlite_ The Column_ type name () method obtains the data for the corresponding column, looping through the loop until the traversal is complete. Finally released via Sqlite3_finalize ().

Code:

1. Create a database

NSString *path = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) objectAtIndex:0];

NSString *filename = [path stringbyappendingpathcomponent:dbname];

2. Open the database and decide whether to open it

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

NSLog (@ "Database open success");

}

else{

NSLog (@ "Database open failure");

}

3, processing a non-return value of SQL statements (such as additions and deletions)

if (sqlite3_exec (database, [SQL Utf8string], nil, nil, &error)! = SQLITE_OK) {

NSLog (@ "%s", error);

}

4. Handle a SQL statement with a return value (such as query)

-(Nsarray *) ExecuteQuery: (NSString *) sql{

Nsmutablearray *array = [[Nsmutablearray alloc]init];

Sqlite3_stmt *stmt;

int result = SQLITE3_PREPARE_V2 (database, [SQL Utf8string],-1, &stmt, NULL);

if (result = = SQLITE_OK) {

while (Sqlite3_step (stmt) = = Sqlite_row) {

Nsmutabledictionary *dic = [[Nsmutabledictionary alloc]init];

for (int i = 0; i < Sqlite3_column_count (stmt); i + +) {

NSString *columnname =[nsstring stringwithutf8string:sqlite3_column_name (stmt, i)];

NSString *value=[nsstring stringwithutf8string: (char *) sqlite3_column_text (stmt, i)];

Dic[columnname] = value;

}

[Array addobject:dic];

}

}

return array;

}

5. Close the database

if (sqlite3_close (database) = SQLITE_OK) {

NSLog (@ "%s", Sqlite3_errmsg (database));

}

Simple data storage--plist, Nskeyedarchiver Archive, Nsuserdefaults (preferences), SQLite (embedded database)

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.