Several data storage methods in iOS development data storage Chapter-ios

Source: Internet
Author: User
Tags sqlite database xml attribute

Several data storage methods in iOS development data storage Chapter-ios

Posted on 2016/4/5 21:02:09 421 people read

Category: Data storage

In the development of the project, we often do local cache processing of some data. Offline cached data is typically stored in the sandbox where the app is located. There are generally the following types:

1. PList (XML attribute list)

The use of plist for data storage and reading, only for some of the system's own common types to use, and must first get the path relative trouble

//写入文件NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];NSString *path = [doc stringByAppendingPathComponent:@"myself.plist"];NSDictionary *dict = @{@"name": @"yixiang"};[dict writeToFile:path atomically:YES];//读取文件NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];

2. Preference settings (nsuserdefaults)

Keep everything under the same folder and use it to store settings for your app.

//写入文件NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];[defaults setObject:@"yixiang" forKey:@"name"];[defaults setInteger:27 forKey:@"age"];[defaults synchronize];//读取文件NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];NSString *name=[defaults objectForKey:@"name"];NSInteger age=[defaults integerForKey:@"age"];
3. Archive (nscoding nskeyedarchiver nskeyedunarchiver)

Because the first two have a fatal flaw, only the commonly used types can be stored. Archiving allows you to store your custom objects in a file.

Objects that need to be saved must adhere to the Nscoding protocol and implement the Protocol-(void) Encodewithcoder: (Nscoder) Acoder and-(ID) Initwithcoder: (Nscoder) Adecoder method.

The YXPerson.h file is as follows:

  @interface YXPerson : NSObject<NSCoding> @property(nonatomic,copy) NSString *name; @property(nonatomic,assign) int age; @end

The yxperson.m file is as follows:

  #import"YYPerson.h"@implementationYyperson-(void) Encodewithcoder: (Nscoder *) acoder{[Acoder encodeobject:Self. Name forkey:@"name"]; [Acoder Encodeinteger: Self, ageforkey:@' age '];}-(ID) Initwithcoder: (Nscoder *) adecoder{ if (  self=[Super init] {self . Name=[adecoder decodeobjectforkey:@"name"]; self. Age=[adecoder decodeintegerforkey:@' age ';} return self ;} @end

Write and read it in Viewcontroller

    //写入对象    YXPerson *p=[[YXPerson alloc]init];    p[email protected]"yixiang";    p.age=27; NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]; NSString *path=[docPath stringByAppendingPathComponent:@"person.yixiang"]; [NSKeyedArchiver archiveRootObject:p toFile:path]; //读取对象 YXPerson *p=[NSKeyedUnarchiver unarchiveObjectWithFile:path];

4. SQLite database

None of the above three methods can store large quantities of data and have performance problems.

The following is a brief introduction, how to open the database, add a table, and then the operation of the additional pruning.

- (void) opendb{Get database file pathNSString *doc = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask,YES) Lastobject];NSString *filename = [Doc stringbyappendingpathcomponent:@"Students.sqlite"];Converts an OC string to a C-language stringConstChar *cfilename = FileName. utf8string;Open the database file (the function automatically creates the database file if the database file does not exist)int result = Sqlite3_open (cFileName, &_db);if (result = = SQLITE_OK) {Open successNSLog (@"Open database Successfully"); }else{NSLog (@"Failed to open database"); }}- (void) createtable{Create a tableConstChar *sql ="CREATE TABLE IF not EXISTS t_student (ID integer PRIMARY KEY autoincrement,name text not null,age integer not NULL);";Char *errmsg=NULL;int result = SQLITE3_EXEC (_db, SQL,NullNULL, &errmsg);if (RESULT==SQLITE_OK) {NSLog (@"CREATE table Success"); }else{NSLog (@"Failed to create table---%s", errmsg); }}- (void) insertdata{Inserting datafor (int i=0; i<10; i++) {Splicing SQL statementsNSString *name = [NSString stringwithformat:@"Yixiangboy--%d", Arc4random_uniform (100)];int age = Arc4random_uniform (20) +10;NSString *sql = [NSString stringwithformat:@"INSERT into T_student (name,age) VALUES ('%@ ',%d);", Name,age];Execute SQL statementChar *errmsg =NULL; Sqlite3_exec (_db, SQL. Utf8string,NullNULL, &errmsg);if (errmsg) {If there is an error messageNSLog (@"Insert data failed--%s", errmsg); }else{NSLog (@"Insert data Success"); } }}- (void) deletedata{Delete data with age less than 15NSString *sql = [NSString stringwithformat:@"DELETE from T_student WHERE age<15"];Char *errmsg =NULL; Sqlite3_exec (_db, SQL. Utf8string,NullNULL, &errmsg);if (errmsg) {NSLog (@"Delete data failed"); }else{NSLog (@"Delete data success"); }}- (void) updatedata{Older than 20 years old are set to 20 years old.NSString *sql = [NSString stringwithformat:@"UPDATE t_student set age=20 WHERE age>20"];Char *errmsg =NULL; Sqlite3_exec (_db, SQL. Utf8string,NullNULL, &errmsg);if (errmsg) {NSLog (@"Failed to update data"); }else{NSLog (@"Update data Success"); }}- (void) querydata{ConstChar *sql ="Select Id,name,age from T_student WHERE age<20"; Sqlite3_stmt *stmt =NULL;Preparation before queryingif (SQLITE3_PREPARE_V2 (_db, SQL,-1, &stmt,NULL) ==SQLITE_OK) {No problem with SQL statementsNSLog (@"Query Statement no problem");//each call sqlite3_step function, stmt will point to the next record while (Sqlite3_step ( stmt) ==sqlite_row) {//find a record //take out data //(1) Take out the value of the No. 0 field (int) int id=sqlite3_column_int (stmt, 0); //(2) Remove the value of the first column field (text) const  unsigned char *name = Sqlite3_column_text (stmt, 1); //(3) takes out the value of the second column field (int) int age = Sqlite3_column_int (stmt, 2); printf ( "%d%s%d\n", Id,name,age);}} else{nslog (@ "query statement problematic");}}   
5, FMDB

Fmdb is an open source project for a well-known SQLite database operation in iOS. The project address is: Https://github.com/ccgus/fmdb

。 is the C language interface of the Sqliite database is a layer of encapsulation, so that it satisfies the object-oriented operation, the interface is much simpler than the native SQLite interface. It also provides a number of multi-threading, caching, thread pool functions. Later blogs will be introduced in detail, there is not much to say.

6, CoreData

is a solution to the data persistence offered by Apple. Later blogs will be introduced in detail, there is not much to say.

Contact information

Weibo: Sina Weibo

Blog: http://blog.csdn.net/yixiangboy

Github:https://github.com/yixiangboy

Several data storage methods in iOS development data storage Chapter-ios

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.