1. Data archiving
First get the path: filepath= [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES). FirstObject stringbyappendingpathcomponent:@ "Person.data"];
Then set the data to be stored and store nsstring *[email protected] "awdasf";
BOOL issuccess=[nskeyedarchiver archiverootobject:strvalue Tofile:filepath];
Remove data
NSString *str=[nskeyedunarchiver Unarchiveobjectwithfile:filepath];
Store multiple classes of data in an archive
Prepare the data first
Cgpoint point = Cgpointmake (10.0, 20.0);
NSString *info = @ "coordinate point";
Nsinteger value = 100;
Set file path
Manypath = [Nshomedirectory () stringbyappendingpathcomponent:@ "Many.archiver"];
Nsmutabledata *data = [[Nsmutabledata alloc]init];
Nskeyedarchiver *archvier = [[Nskeyedarchiver alloc]initforwritingwithmutabledata:data];
Archiving multiple Data Objects
[Archvier encodecgpoint:point forkey:@ "Kpoint"];
[Archvier encodeobject:info forkey:@ "Kinfo"];
[Archvier encodeinteger:value forkey:@ "Kvalue"];
[Archvier finishencoding];
[Data Writetofile:multihomepath Atomically:yes];
Get data from a file
Nsmutabledata *datar = [[Nsmutabledata Alloc]manypath];
Nskeyedunarchiver *unarchiver = [[Nskeyedunarchiver Alloc]initforreadingwithdata:datar];
Cgpoint pointr = [Unarchiver decodecgpointforkey:@ "Kpoint"];
NSString *infor = [Unarchiver decodeobjectforkey:@ "Kinfo"];
Nsinteger valuer = [Unarchiver decodeintegerforkey:@ "Kvalue"];
[Unarchiver finishdecoding];
2. Accessing Data using Nsuserdefault
Define Nsuserdefault objects, store data
Nsuserdefaults *defaults=[nsuserdefaults Standarduserdefaults];
NSString *[email protected] "defaults string";
[Defaults setobject:strvalue forkey:@ "StrName"];
Remove Data
NSString *strvalue=[defaults objectforkey:@ "StrName"];
3. Using the SQLite database
First introduce frame libsqlite3.0
Defining Global Variables
Sqlite3 *m_db;
Setting the database path
Nsarray *paths=nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
NSString *strpath=[paths objectatindex:0];
NSString *strfinalpath=[strpath stringbyappendingstring:@ "Personinfo.sqlite"];
Open or create a database
if (Sqlite3_open ([Strfinalpath utf8string], &m_db)!=SQLITE_OK)
{
Sqlite3_close (m_db);
NSLog (@ "Database open failed");
}
Creating a data Table Personinfo
NSString *[email protected] "CREATE TABLE IF not EXISTS PERSONINFO (ID INTEGER PRIMARY KEY autoincrement,name text,age INTE Ger,address TEXT) ";
[Self executesql:strcreatetable];
Inserting data
Strinsertdate=[nsstring stringwithformat:@ "INSERT into '%@ ' ('%@ ', '%@ ', '%@ ') VALUES ('%@ ', '%@ ', '%@ ')", @ "PERSONINFO", @ "name", @ "address", @ "age", username,useraddress,userage];
[Self executesql:strinsertdate];
Update data
Strupdate=[nsstring stringwithformat:@ "UPDATE%@ SET address= '%@ ' WHERE%@= '%@ '", Tablename,straddress,valuename, Strsearch];
[Self executesql:strupdate];
Delete data
Strdelete=[nsstring stringwithformat:@ "DELETE from%@ WHERE%@= '%@ '", Tablename,valuename,strsearch];
[Self executesql:strdelete];
Execute all SQL statements except the query
-(void) ExecuteSQL: (nsstring*) M_sql
{
Char *error;
if (Sqlite3_exec (m_db, [m_sql utf8string], NULL, NULL, &ERROR)!=SQLITE_OK)
{
Sqlite3_close (m_db);
NSLog (@ "SQL statement execution failed");
}
}
Querying the database
SQLQuery = [NSString stringwithformat:@ "SELECT * from%@", strdatabase];
SQLQuery = [NSString stringwithformat:@ "select * from%@ WHERE%@= '%@ '", Strdatabase,strvaluename,strvalue];
SQLITE3_STMT * statement;
if (Sqlite3_prepare_v2 (m_db, [SQLQuery utf8string],-1, &statement, nil) = = SQLITE_OK) {
while (sqlite3_step (statement) = = Sqlite_row) {
If present, get the data
Char *name = (char*) sqlite3_column_text (statement, 1);
NSString *nsnamestr = [[NSString alloc]initwithutf8string:name];
int age = Sqlite3_column_int (statement, 2);
NSString *nsagestr=[nsstring stringwithformat:@ "%d", age];
Char *address = (char*) sqlite3_column_text (statement, 3);
NSString *nsaddressstr = [[NSString alloc]initwithutf8string:address];
}
}
Sqlite3_close (m_db);
4. Using Fmdb database (operation is more convenient than SQLite, need to introduce class library)
Defining global variables
Fmdatabase *m_db;
NSString *strfinalpath;
Setting the database path
Nsarray *paths=nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
NSString *strpath=[paths objectatindex:0];
Strfinalpath=[strpath stringbyappendingstring:@ "Personinfo.sqlite"];
Create a database
M_db=[fmdatabase Databasewithpath:strfinalpath];
Create a table
-(void) createtable
{
if ([m_db Open]) {
NSString *sqlcreatetable = [NSString stringwithformat:@ "CREATE TABLE IF not EXISTS '%@ ' ('%@ ' INTEGER PRIMARY KEY AUTOINC Rement, '%@ ' text, '%@ ' INTEGER, '%@ ' text ', @ ' PERSONINFO ', @ ' ID ', @ ' name ', @ ' age ', @ ' adress '];
BOOL res = [m_db executeupdate:sqlcreatetable];
if (!res) {
NSLog (@ "error when creating DB table");
} else {
NSLog (@ "Success to creating DB table");
}
[m_db Close];
}
}
Inserting data
-(void) InsertData
{
if ([m_db Open]) {
NSString *insertsql1= [NSString stringWithFormat:
@ "INSERT into '%@ ' ('%@ ', '%@ ', '%@ ') VALUES ('%@ ', '%@ ', '%@ ')",
@ "PERSONINFO", @ "name", @ "age", @ "adress", @ "YT", @ "123", @ "XT"];
BOOL res = [m_db EXECUTEUPDATE:INSERTSQL1];
NSString *INSERTSQL2 = [NSString stringWithFormat:
@ "INSERT into '%@ ' ('%@ ', '%@ ', '%@ ') VALUES ('%@ ', '%@ ', '%@ ')",
@ "PERSONINFO", @ "name", @ "age", @ "adress", @ "yy", @ "124", @ "BJ"];
res = [m_db executeupdate:insertsql2];
if (!res) {
NSLog (@ "error when insert DB table");
} else {
NSLog (@ "Success to insert DB table");
}
[m_db Close];
}
}
Update data
-(void) UpdateData
{
if ([m_db Open]) {
NSString *updatesql = [NSString stringWithFormat:
@ "UPDATE '%@ ' SET '%@ ' = '%@ ' WHERE '%@ ' = '%@ '",
@ "PERSONINFO" @ "age" @ "at" @ "age" @ "13"];
BOOL res = [m_db executeupdate:updatesql];
if (!res) {
NSLog (@ "error when update db table");
} else {
NSLog (@ "Success to update DB table");
}
[m_db Close];
}
}
Delete data
-(void) DeleteData
{
if ([m_db Open]) {
NSString *deletesql = [NSString stringWithFormat:
@ "Delete from%@ where%@ = '%@ '",
@ "PERSONINFO", @ "name", @ "Zhang San"];
BOOL res = [m_db executeupdate:deletesql];
if (!res) {
NSLog (@ "error when delete db table");
} else {
NSLog (@ "Success to delete db table");
}
[m_db Close];
}
}
Querying data
-(void) Searchdata
{
if ([m_db Open]) {
NSString * sql = [NSString stringWithFormat:
@ "SELECT * from%@" @ "PERSONINFO"];
Fmresultset * rs = [m_db executequery:sql];
while ([Rs next]) {
int id = [RS intforcolumn:@ "id"];
NSString * name = [rs stringforcolumn:@ "name"];
NSString * age = [rs stringforcolumn:@ ' age '];
NSString * address = [RS stringforcolumn:@ "address"];
NSLog (@ "id =%d, name =%@, age =%@ address =%@", ID, name, age, address);
}
[m_db Close];
}
}
Example of reading change data using an asynchronous operation
-(void) Asyncqueue
{
Fmdatabasequeue * queue = [Fmdatabasequeue Databasequeuewithpath:strfinalpath];
dispatch_queue_t q1 = dispatch_queue_create ("queue1", NULL);
dispatch_queue_t q2 = dispatch_queue_create ("Queue2", NULL);
Dispatch_async (Q1, ^{
for (int i = 0; i <; ++i) {
[Queue indatabase:^ (Fmdatabase *db2) {
NSString *insertsql1= [NSString stringWithFormat:
@ "INSERT into '%@ ' ('%@ ', '%@ ', '%@ ') VALUES (?,?,?)",
@ "PERSONINFO", @ "name", @ "age", @ "address";
NSString * name = [NSString stringwithformat:@ "Jack%d", I];
NSString * age = [NSString stringwithformat:@ "%d", 10+i];
BOOL res = [DB2 EXECUTEUPDATE:INSERTSQL1, Name, age,@ "XT"];
if (!res) {
NSLog (@ "error to Inster data:%@", name);
} else {
NSLog (@ "SUCC to Inster Data:%@", name);
}
}];
}
});
Dispatch_async (Q2, ^{
for (int i = 0; i <; ++i) {
[Queue indatabase:^ (Fmdatabase *db2) {
NSString *insertsql2= [NSString stringWithFormat:
@ "INSERT into '%@ ' ('%@ ', '%@ ', '%@ ') VALUES (?,?,?)",
@ "PERSONINFO", @ "name", @ "age", @ "address";
NSString * name = [NSString stringwithformat:@ "Lilei%d", I];
NSString * age = [NSString stringwithformat:@ "%d", 10+i];
BOOL res = [DB2 executeupdate:insertsql2, Name, age,@ "BJ"];
if (!res) {
NSLog (@ "error to Inster data:%@", name);
} else {
NSLog (@ "SUCC to Inster Data:%@", name);
}
}];
}
});
}
IOS Data storage