4 ways to persist iOS data

Source: Internet
Author: User
Tags sqlite database

9.1 Overview of data persistence

9.2 iOS Application directory structure

9.3 List of Read and write properties

9.4 Object Archiving

9.5 Visit SQLite

9.1 Overview of data persistence

There are four ways to persist data in iOS: Attribute list, Object archive, SQLite3, and core data

9.2 iOS Application directory structure

iOS app runs on Mac OS Simulator, there is a temporary directory emulator 3.1.3 For example:

/users/tony/library/application Support/iphone simulator/3.1.3/applications

The iOS app is designed in a sandbox-based design, with iOS each with its own 3 directories (DOCUMENT,LIBRARY,TMP) that are inaccessible to one another.

Documents to store data for the application.

The Library directory also contains the preferences and caches directories, preferences directory for application preferences, caches directory is similar to documents that can hold application data.

The TMP directory is used by the application to store temporary files.

9.3 List of Read and write properties

Read files in the documents directory

You can get the Documents folder for your application.

    nsarray* mypaths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);    nsstring* Mydocpath = [Mypaths objectatindex:0];

Gets the full path of the file.

-(nsstring*) FilePath: (nsstring*) fileName {    nsarray* mypaths = Nssearchpathfordirectoriesindomains ( NSDocumentDirectory, Nsuserdomainmask, YES);    nsstring* Mydocpath = [mypaths objectatindex:0];    nsstring* FilePath = [Mydocpath stringbyappendingpathcomponent:filename];    return FilePath;}

Get the TMP directory

Getting the application's TMP directory is much easier than getting the documents directory. Use the function nstemporarydirectory () to get the TMP directory path.

nsstring* TempPath = Nstemporarydirectory ();

Gets the full path of the file.

nsstring* tempfile = [TempPath stringbyappendingpathcomponent:@ "Properties.plist"];

Attribute list File instance: Properteslist

PropertesListViewController.h

#import "Student.h" @interface Viewcontroller:uiviewcontroller@property (Retain, nonatomic) iboutlet Uitextfield * Studentno; @property (retain, nonatomic) Iboutlet Uitextfield *studentname; @property (retain, nonatomic) Iboutlet Uitextfield *studentclass;-(ibaction) Save: (ID) sender;-(ibaction) Load: (ID) sender;-(ibaction) endediting: (ID) sender;-(ibaction) Savetoarchiver: (ID) sender;-(ibaction) Loadfromarchiver: (ID) sender;-(nsstring*) FilePath: ( nsstring*) FileName; @end

Properteslistviewcontroller.m

@synthesize Studentno; @synthesize studentname; @synthesize studentclass;-(nsstring*) FilePath: (nsstring*) FileName {    nsarray* mypaths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);    nsstring* Mydocpath = [Mypaths objectatindex:0];    nsstring* FilePath = [Mydocpath stringbyappendingpathcomponent:filename]; return FilePath;}    -(Ibaction) Save: (ID) Sender {nsstring* fileName = [self filepath:@ "properties.plist"];    NSLog (FileName);    nsmutablearray* data = [[Nsmutablearray alloc]init];    [Data AddObject:studentNo.text];    [Data AddObject:studentName.text];    [Data AddObject:studentClass.text]; [Data Writetofile:filename atomically:yes];}    -(ibaction) Load: (ID) Sender {nsstring* fileName = [self filepath:@ "properties.plist"]; if ([[[Nsfilemanager Defaultmanager]fileexistsatpath:filename]) {nsarray* data = [[Nsarray alloc]initwithcontentsof]        File:filename];        Studentno.text = [data objectatindex:0]; Studentname.text =[Data objectatindex:1];        Studentclass.text = [data objectatindex:2];    [Data release]; }}-(Ibaction) endediting: (ID) Sender {[sender resignfirstresponder];}

9.4 Object Archiving

Object Archive instance: Encoding

Object archiving

"Archive" is another form of serialization, the technology of archiving model objects can easily write complex objects to the file, and then read them, as long as each property implemented in the class is a basic data type (such as int or float) or an instance of a class that conforms to the nscoding protocol. You can have a full archive of your objects.

Implementing the Nscoding Protocol

The Nscoding protocol declares two methods:-(void) Encodewithcoder: (Nscoder *) Acoder, which writes an object to a file.

-(ID) Initwithcoder: (Nscoder *) Adecoder, is to read the data in the file into the object.

Implementing the Nscopying Protocol

The Nscopying protocol declares a method:-(ID) Copywithzone: (Nszone *) zone, which is the method of copying objects.

Student.h

@interface student:nsobject<nscoding, nscopying> @property (retain, nonatomic) nsstring* Studentno; @property ( Retain, nonatomic) nsstring* Studentname, @property (retain, nonatomic) nsstring* StudentClass; @end

Student.m

#import "Student.h" @implementation student@synthesize studentno = _studentno; @synthesize studentname = _studentname;@ Synthesize studentclass = _studentclass; #pragma mark nscopying-(ID) Copywithzone: (Nszone *) Zone {student* copy = [[[SE    LF Class]allocwithzone:zone]init];    Copy.studentno = [_studentno copywithzone:zone];    Copy.studentname = [_studentname copywithzone:zone];    Copy.studentclass = [_studentclass copywithzone:zone]; return copy;}     #pragma mark nscoding-(void) Encodewithcoder: (Nscoder *) Acoder {[Acoder encodeobject:_studentno forkey:@ "Studentno"];    [Acoder encodeobject:_studentname forkey:@ "Studentname"]; [Acoder encodeobject:_studentclass forkey:@ "StudentClass"];}    -(ID) Initwithcoder: (Nscoder *) adecoder {_studentno = [adecoder decodeobjectforkey:@ "Studentno"];    _studentname = [Adecoder decodeobjectforkey:@ "Studentname"];    _studentclass = [Adecoder decodeobjectforkey:@ "StudentClass"]; return self;} -(nsstring*) Description {return [[[NSString A]lloc]initwithformat:@ "no:%@ name:%@ class:%@", _studentno, _studentname, _studentclass]autorelease];}    -(void) Dealloc {[_studentname release];    [_studentclass release];    [_studentno release]; [Super Dealloc];} @end

EncodingViewController.h

See more in detail.

Encodingviewcontroller.m

-(Ibaction) Savetoarchiver: (ID) Sender {    nsstring* fileName = [self filepath:@ "student.archiver"];    nsmutabledata* data = [Nsmutabledata data];    nskeyedarchiver* archiver = [[Nskeyedarchiver alloc]initforwritingwithmutabledata:data];    student* Student = [[Student alloc]init];    Student.studentno = Studentno.text;    Student.studentname = Studentname.text;    Student.studentclass = Studentclass.text;    [Archiver encodeobject:student forkey:@ "Mystudent"];    [Archiver finishencoding];    [Data Writetofile:filename Atomically:yes];    [Archiver release];    [Student release];}

Nsmutabledata * Thedata = [Nsmutabledata data];

Nskeyedarchiver * archiver = [[Nskeyedarchiver alloc] initforwritingwithmutabledata:thedata]; Create NSKeyedArchiver instance, Used to archive an object into this thedata instance.

[Archiver encodeobject:student forkey:@ "Mystudent"]; Use the key-value pair encoding to archive the objects that you want to include in the archive.

[Thedata writetofile:filename Atomically:yes]; Write data to an archive file.

Encodingviewcontroller.m

-(Ibaction) Loadfromarchiver: (ID) Sender {    nsstring* fileName = [self filepath:@ "student.archiver"];    nsdata* data = [NSData datawithcontentsoffile:filename];    if ([data length] > 0) {        nskeyedunarchiver* unarchiver = [[Nskeyedunarchiver alloc]initforreadingwithdata:data];        student* Student = [Unarchiver decodeobjectforkey:@ "Mystudent"];        Studentno.text = Student.studentno;        Studentname.text = Student.studentname;        Studentclass.text = Student.studentclass;        [Unarchiver finishdecoding];        [Unarchiver release];}    }

NSData * thedata =[nsdata datawithcontentsoffile:filename]; Get NSData instances from the archive file.

Nskeyedunarchiver * archiver = [[Nskeyedunarchiver alloc] initforreadingwithdata:thedata];

Creates a Nskeyedunarchiver instance to decode the data. Student *student = [archiver decodeobjectforkey:@ "Mystudent"];

Use the same Key object as the archive encoding to decode it.

9.5 Visit SQLite

SQLite database

SQLite is an open-source embedded relational database, which was made in 2000 by D. Richard Hipp released, which reduces the overhead of application management data, SQLite portability is good, easy to use, small, efficient and reliable.

SQLite is embedded in applications that use it, and they share the same process space instead of a single process. Externally, it's not like an RDBMS, but inside the process it's a complete, self-contained database engine. One of the great benefits of an embedded database is that you don't need a network configuration or management within your program. Because the client and the server are running in the same process space. SQLite's database permissions depend only on the file system, without the concept of a user account. SQLite has a database-level lock and no network server. It requires less memory, other overhead, and is suitable for use in embedded devices. All you need to do is to compile it correctly into your program.

SQLite data types

SQLite is untyped, which means that you can save any type of data into any column of any table you want to save, without

On what type of data this column declares, it is completely valid for SQLite to not specify a type for a field, such as:

Create Table Ex1 (A, B, c);

SQLite allows data types to be ignored, but it is still recommended to specify the data type in your CREATE TABLE statement because the data type is for you to communicate with other programmers, or you are ready to replace your database engine. SQLite supports common data types, such as:

Using SQLite3 in iOS

In order to be able to use SQLite3 in iOS it is necessary to add the Libsqlite3.dylib class library to the Xcode project, right-click on the project's frameworks (frames) folder to add the presence frameworks

or navigate to/developer/platforms/iphonesimulator.platform/developer/sdks/iphonesimulator<version>.sdk/usr/lib. Directory below to find Libsqlite3.dylib.

Example: StudentSQLite3

StudentSQLite3ViewController.h

#import "sqlite3.h" #define Data_file @ "DATA.SQLITE3" #define TABLE_NAME @ "Student" #define FIELDS_NAME_SID @ "StudentID" #define FIELDS_NAME_SNAME @ "Studentname" #define Fields_name_sclass @ "StudentClass" @interface Viewcontroller: Uiviewcontroller {    sqlite3* db;} @property (Retain, nonatomic) Iboutlet Uitextfield *studentid; @property (retain, nonatomic) iboutlet Uitextfield * Studentname; @property (retain, nonatomic) Iboutlet Uitextfield *studentclass;-(ibaction) Savefromsqlite: (ID) sender;- (ibaction) Loadfromsqlite: (ID) sender;-(nsstring*) datafile;-(ibaction) textfielddoneediting: (ID) sender; @end

Studentsqlite3viewcontroller.m

@synthesize StudentID; @synthesize studentname; @synthesize studentclass;-(nsstring*) datafile {    nsarray* mypaths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);    nsstring* Mydocpath = [mypaths objectatindex:0];    nsstring* fileName = [Mydocpath stringbyappendingformat:data_file];    return fileName;}

Non-parametric SQLite3 process

1. Open the database Sqlite3_open.

2. Create database tables and execute SQL statement sqlite3_exec.

3, Release resources Sqlite3_close.

Create a database

-(void) viewdidload {    [super viewdidload];    nsstring* fileName = [self datafile];    NSLog (@ "%@", fileName);    if (Sqlite3_open ([FileName utf8string], &db)! = SQLITE_OK) {        sqlite3_close (db);        Nsassert (NO, @ "OPEN SQLITE DATABASE error! ");    } else {        char* error;        
TABLE_NAME, FIELDS_NAME_SID, Fields_name_sname, Fields_name_sclass]; if (sqlite3_exec (DB, [Createsql utf8string], NULL, NULL, &error)) { sqlite3_close (db); NSAssert1 (NO, @ "CREATE TABLE error", error); } else { sqlite3_close (db);}}}

Sqlite3_open ([[Self DataFilePath] utf8string], &db)! = SQLITE_OK Sqlite3_open Open database, note: Functions in Sqlite3 are using C string [self DataFilePath] utf8string] is the address of the sqlite3 pointer (* db) that converts the NSString string to a C string.

The function Sqlite3_open returns SQLITE_OK open successfully.

Sqlite3_exec (DB, [Tablesql utf8string], NULL, NULL, &ERR)! = SQLITE_OK

Sqlite3_exec is to execute any SQL statement without a return value, the 2nd parameter is the SQL statement to execute, the 3rd parameter is the callback function, the 4th parameter is the parameter to the callback function, and the 5th parameter is the string that performs the error.

Sqlite3_close (DB); is to close the database.

Nsassert is an assertion function that prints information when an assertion fails.

NSAssert1 is a nsassert function with a parameter, in addition to functions such as NSAssert2.

SQLite3 process with parameters

1. Open the database Sqlite3_open.

2, preprocessing SQL statement sqlite3_prepare_v2.

3, binding parameter Sqlite3_bind_text.

4, execute the statement sqlite3_step (statement).

5, Release resources Sqlite3_finalize?sqlite3_close.

Data saving

-(Ibaction) Savefromsqlite: (ID) Sender {nsstring* fileName = [self datafile];    NSLog (@ "%@", fileName);        if (Sqlite3_open ([FileName utf8string], &db)) {sqlite3_close (db);    Nsassert (NO, @ "OPEN DATABASE ERROR"); } else {nsstring* sqlstr = [NSString stringwithformat:@ "INSERT OR REPLACE into%@ (%@,%@,%@) VALUES (?,?,?)", Tab        Le_name, Fields_name_sid, Fields_name_sname, Fields_name_sclass];        sqlite3_stmt* statement;            Preprocessing procedure if (Sqlite3_prepare (DB, [Sqlstr utf8string], 1, &statement, NULL) = = SQLITE_OK) {//bind parameter start            Sqlite3_bind_text (statement, 1, [Studentid.text utf8string],-1, NULL);            Sqlite3_bind_text (statement, 2, [Studentname.text utf8string],-1, NULL);            Sqlite3_bind_text (statement, 3, [Studentclass.text utf8string],-1, NULL);            Perform an Insert if (SQLITE3_STEP (statement)! = Sqlite_done) {nsassert (0, @ "Insert DATABASE error!"); }} SQlite3_finalize (statement);    Sqlite3_close (DB); }}

SQLITE3_PREPARE_V2 (DB, [Sqlstr utf8string], 1, &statement, nil) = = Sqlite_ok

SQLITE3_PREPARE_V2 executes the SQL statement, the 3rd parameter-1 represents the length of all SQL strings, and the 4th parameter &statement is the address of the SQLITE3_STMT pointer (* statement). The 5th parameter is a partial statement that the SQL statement is not executed.

Sqlite3_bind_text (statement, 1, [Studentid.text utf8string],-1, NULL);

is a binding parameter, the 2nd argument is ordinal (starting at 1), the 3rd argument is a string value, and the 4th argument is the string length. The 5th parameter is a function pointer, which SQLITE3 the function after execution, and is typically used to free memory occupied by the string.

SQLITE3_STEP (statement)! = Sqlite_done Determines whether execution completes the SQL statement execution.

Sqlite3_finalize (statement) and Sqlite3_close (DB) Release resources.

Querying data

-(Ibaction) Loadfromsqlite: (ID) Sender {nsstring* fileName = [self datafile];    NSLog (@ "%@", fileName);        if (Sqlite3_open ([FileName utf8string], &db)! = SQLITE_OK) {sqlite3_close (db); Nsassert (NO, @ "OPEN DATABASE error!");}                             else {nsstring* sqlstr = [NSString stringwithformat:@ "select%@,%@,%@ from%@ WHERE%@=?",        Fields_name_sid, Fields_name_sname, Fields_name_sclass, TABLE_NAME, FIELDS_NAME_SID];        sqlite3_stmt* statement; Preprocessing procedure if (SQLITE3_PREPARE_V2 (DB, [Sqlstr utf8string], 1, &statement, NULL) = = SQLITE_OK) {//bind parameter            Start Sqlite3_bind_text (statement, 1, "N",-1, NULL); Execute while (sqlite3_step (statement) = = Sqlite_row) {char* field1 = (char*) Sqlite3_column_text (s                Tatement, 0);                nsstring* field1str = [[NSString alloc]initwithutf8string:field1];                                Studentid.text = Field1str; char* Field2 = (char*) sqlite3_column_text (statement, 1);                nsstring* field2str = [[NSString alloc]initwithutf8string:field2];                                Studentname.text = Field2str;                char* field3 = (char*) sqlite3_column_text (statement, 2);                nsstring* field3str = [[NSString alloc]initwithutf8string:field3];                                Studentclass.text = Field3str;                [Field1str release];                [Field2str release];            [Field3str release];        }} sqlite3_finalize (statement);    Sqlite3_close (DB); }}

while (sqlite3_step (statement) = = Sqlite_row) sqlite3_step (statement) = = Sqlite_row stepping through and judging the state of the SQL statement execution.

Char *field1 = (char *) sqlite3_column_text (statement, 0); Sqlite3_column_text (statement, 0); The field value is taken out, and the 2nd parameter is the order of the columns, starting with 0.

NSString *field1str = [[NSString alloc] initwithutf8string:field1]; build nssting string.

Other parts of the code

-(Ibaction) textfielddoneediting: (ID) sender {    [sender Resignfirstresponder];} -(void) viewdidunload{    [self setstudentid:nil];    [Self setstudentname:nil];    [Self setstudentclass:nil];    [Super Viewdidunload];} -(void) dealloc {    [StudentID release];    [Studentname release];    [StudentClass release];    [Super Dealloc];}

4 ways to persist 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.