15 Data Persistence
-
Upload
sworna-vidhya-mahadevan -
Category
Documents
-
view
214 -
download
0
Transcript of 15 Data Persistence
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 1/14
12/12/11
1
Data Persistence
Amit Gulati
Data Persistence
} Persistent storage
} Any form of non-volatile storage that survives a restart of the device.
} Devices that run iOS have only internal permanent storage
} External storage via SD card is not supported
} Internal Storage can be 16 GB, 32 GB and 64 GB.
} Applications can store files, data etc in their sand boxes and
are restricted by the device storage limit.
} In the real world, applications need to persist data
} Application Preferences/Settings
} Application Data
} Database
} Objects
} Files etc.2
Data Persistence
} A number of different mechanisms are available for persisting
data on the iOS.
} Property List Serialization
} Object Archives
} File System
} SQLite (Relational Database)
} Core Data
3
Property List Serialization
Amit Gulati
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 2/14
12/12/11
2
Property List
} Property Lists are used to express simple hierarchies of data.
} Property Lists are any combination of the following classes} Containers
} NSArray, NSMutableArray
} NSDictionary, NSMutableDictionary
} Primitive Types
} NSString, NSMutableString
} NSData, NSMutableData
} NSDate
} NSNumber
} A common use of Property List is to persist applicationpreference / settings data.
5
Property List
} Root of Property List is generally a container (but does nothave to be)
} If Root of property list is not a container, then property list will be just asingle value.
} Examples
6
Property List Serialization
} Forms of Property List
} In memory as
} NSArray, NSDictionary, NSData etc.
} File
} XML file
¨ Popular format in iOS
¨ Highly transportable across file systems and networks.
} Binary file
¨ Compact and suitable for large property lists.
There is another ASCII text format for Property List file, but that
is not supported by iOS.
7
Property List Serialization
} Property Lists are a convenient way to persist data topermanent store.
} If data is composed of the property list supported objects.
} NSDictionary, NSArray, NSData, NSDate, NSString, NSNumber
} Can be edited easily
} Property list files can be easily edited using the Property List Editor application.
} XML format of property list can be edited us ing a simple editor.
} Property list files can easily be converted to Container types} If root of property list is NSDictionary or NSArray.
} NSDictionary and NSArray classes have methods to read and write property list
file data.
8
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 3/14
12/12/11
3
Property List Serialization
} There are two ways of persisting property list to a file
} Methods of collection classes (NSDictionary, NSArray etc.)
} Just create a collection object
} Write the collection object to persistent store.
} Only supports XML based property list file.
} NSPropertyListSerialization class
} Supports property list file using different formats.
Methods of collection classes
} Persisting data contained in NSArray / NSDictionary toProperty List file
} Use either an NSArray or an NSDictionary to hold the data (key valuepairs) that needs to be persisted.
} Call the function writeToFile:atomically: to write the property listto a file.
path, Path (including the file name) where the property list file will bewritten.
flag, If YES, data is first written to a temporary file, once successfulthe temporary file is copied to the path specified.
This ensures that corrupted file is not written (in case the writeprocess is interrupted because of loss of batter y or system crash etc.)
10
-(BOOL) writeToFile: (NSString *)path atomically: (BOOL)flag
Methods of collection classes
} Reading data from a Property List file into NSDictionary
} Functions are provided that allow you to read data from a property listfile into NSDictionary
This function creates a new dictionary and fills it with key value pair datastored in the plist file.
path, Path (including the file name) where the property list file exists.
The file identified by path must contain a string representation
of a property list whose root object is a dictionary.
NSDictionary
NSDictionary returned is autoreleased.Remember to call “retain”.
11
+ (id)dictionaryWithContentsOfFile: (NSString *)path
Methods of collection classes
} Reading data from a Property List file into NSArray
} Functions are provided that allow you to read data from a property listfile into NSArray
This function creates a new array and fills it with key value pair data storedin the plist file
path, Path (including the file name) where the property list file exists.
The file identified by path must contain a string representationof a property list whose root object is an array.
NSArray
NSArray returned is autoreleased.Remember to call “retain”.
12
+ (id)array WithContentsOfFile: (NSString *)path
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 4/14
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 5/14
12/12/11
5
NSPropertyListSerialization
} Reading data from a Property List file into NSDictionary /NSArray
} Method to read data in property list file to NSData
+ (id) dataWithContentsOfFile: (NSString *) path
- (id) initWithContentsOfFile: (NSString *)path
+ (id) dataWithContentsOfURL: (NSURL *) url
- (id) initWithContentsOfURL: (NSURL *)aURL
path, Path (including the file name) to the property list file.
url, URL where the property li st file exis ts, currently only, file:// URL
is supported.
17
+ (id) dataWithContentsOfFile: (NSString *) path- (id) initWithContentsOfFile: (NSString *)path
+ (id) dataWithContentsOfURL: (NSURL *) url - (id) initWithContentsOfURL: (NSURL *)aURL
NSPropertyListSerialization
} Reading data from a Property List file into NSDictionary /NSArray
} Methods to convert from NSData to Property List
+ (id) propertyListWithData: (NSData *) dataoptions: (NSPropertyListReadOptions)opt format: (NSPropertyListFormat *) format
error: (NSError **) error
data, A data object containing a serialized property list.
opt, The opt parameter is currently unused and should be set to 0.
format, This value is returned as a pointer is passed.
NSPropertyListXMLFormat_v1_0 for XML format.
NSPropertyListBinaryFormat_v1_0 for binary format.
error , If the method does not complete successfully, upon returncontains an NSError object that describes the problem.
18
+ (id) propertyListWithData: (NSData *) dataoptions: (NSPropertyListReadOptions)opt format: (NSPropertyListFormat *) format
error: (NSError **) error
NSPropertyListSerialization
} Reading data from a Property List file into NSDictionary /NSArray} Methods to convert from NSData to Property List
+ (id) propertyListWithData: (NSData *) datamutabilityOption: (NSPropertyListMutabilityOptions) mutOpt
format: (NSPropertyListFormat *) formaterror: (NSError **) error
mutOpt, Can be one of the following.
NSPropertyListImmutable, Returned property list to containimmutable
objects.
NSPropertyListMutableContainers, Returned property list to havemutable containers but immutable leaves.
NSPropertyListMutableContainersAndLeaves,Returned property listto have mutable containers and leaves.
19
+ (id) propertyListWithData: (NSData *) datamutabilityOption: (NSPropertyListMutabilityOptions) mutOpt
format: (NSPropertyListFormat *) formaterror: (NSError **) error
NSPropertyListSerialization
} Example
20
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 6/14
12/12/11
6
Limitations
} Limitations of using Property List for data persistence
} Good only for simple key-value pair type information.
} The entire property list file contents are loaded in memory
} Not very efficient when the data set becomes large.
} Custom objects cannot be serialized into property lists.
} Not efficient when it comes to large binary data.
21
SQLite
Amit Gulati
SQLite
} RDBMS
} Cross platform
} Open Source.
} Light Weight
} Very small memory footprint.
} Optimized for resource constrained systems and embedded devices.
} Very efficient at storing and retrieving large amounts of data.
} Self Contained
} Not a Server based RDBMS
} Data resides on the device file system, rather than a remote server.
23
Well suited for resourceconstrained systems
SQLite and iOS
} SQLite has been supported since iPhone OS version 1.0
} If you want to support all versions of the iOS/iPhone then SQLite is theonly option (as far as RDBMS).
} Used for persisting data on the phone
} If your application will deal with a large database, use SQLite
} Used by CoreData
} CoreData is Apple’s Ob ject Relationship Technology.
} By default data is written to SQLite database.
} C based API can be easily integrated with Objective-C.
} C APIs can be used freely with Objective-C code.
24
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 7/14
12/12/11
7
Programming SQLite
} Uses the Structured Query Language (SQL).
} SQLite used the standard SQL for reading/writing to the database.
} SQL queries are stored in strings and executed on the database.
} C based API to access data in database
} Simple set of functions to create, update and delete the database.
} Database file format is the same as used for desktop.
} Database can be copied to the desktop and its contents read/writtenusing freely available tools.
} For Example:Database can be populated with default data and included with the application.
25
Country Application
} Database file name
} “country.db”
} Database Schema
26
Columns Data Type Description
id integer Primary Key
name text Name of Country
continent Integer Continent to which the countrybelongs to.
“country” table
Working with SQLite Database
} Free SQLite management tool
} SQLite Studio
} SQLite Browser
} Using the command line
} Sqlite3 provides a command line interface to SQLite database.
27
Command Line Interface
} Creating a new SQLite database file
} Command used to create and open a new database
} Example : Creating the “country.db” database file.
sqlite3 <name of the database file>
28
• File is created if does not already exists.• By default, a database named “main” is added to the “.db” file.
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 8/14
12/12/11
8
Command Line Interface
} Check which databases exist in the file
} Command used to check databases existing in the db file.
} Example : Check databases existing in the “country.db” file.
.databases
29
Working with SQLite Database
} SQLite Command line interface can be used for running SQLcommands and queries.
} Creating database tables
} Example : Creating the “country” tab le in “country.db”.
Working with SQLite Database
} Inserting Data into SQL Database
} Example : Inserting record into the “project” table
Working with SQLite Database
} Querying data from the SQLite database
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 9/14
12/12/11
9
SQLite “C” API
Amit Gulati
Working with SQLite Database
} SQLite database is accessed through a C based API.
} To use this API, we’ll need to link our application to a dynamic
library called libsqlite3.dylib, located in /usr/lib on both Mac OS X
and iPhone.
} The process of linking a dynamic library into your project is
exactly the same as that of linking in a framework.
} Open the project in which you want SQLite access.
} Select Frameworks in the Groups & Files pane . Right click andselect, “Add -> Existing Frameworks”
34
Working with SQLite Database
} Adding the SQLite shared library to the xcode project.
} Select libsqlite3.dylib from the drop down window.
35
Working with SQLite Database
} Adding the SQLite database to project resources
} Once the database file is created and initialized with the schema.
} Add the database file to the project resources
} Drag the database file to the resources folder.
} Example : “taskmanager.db”
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 10/14
12/12/11
10
Working with SQLite Database
} Creating a writeable database
} The database added to resources is read only as resources are part
of the application binary and hence cannot be modified at runtime.
} To work with the database (CRUD operations) we need to create awriteable copy of the database in the application sandbox.
Make a writeablecopy of thedatabase file indocuments folder
Working with SQLite Database
} Creating a writeable database
} Example code to create a writeable copy of the database in the
sandbox.
Working with SQLite Database
} Handle to the database
Each SQLite database is represented by a pointer to an instance of theopaque structure named "sqlite3”.
When we open/create a SQLite database we get a reference to this database
handle.
This handle to the SQLite database is required to work with the database
using the SQLite API.
Example:
sqlite3* database;int success = sqlite3_open(“database path”, &database);…………sqlite3_close(database);
39
sqlite3
Working with SQLite Databases
} Opening/Closing a Database
int, SQLITE_OK return value means the database was opened successfully.
An error value is returned if the database was not successfully opened.
Refer to sqlite3.h for a comprehensive list of all error codes.
filename, Absolute path to the SQLite database file.
ppDb, Pointer to pointer to the sqlite3 structure.} Example:
sqlite3 *database;int result = sqlite3_open(“/path/to/database/file”, &database);
….
sqlite3_close(database);
40
int sqlite3_open(const char *filename, sqlite3 **ppDb)
int sqlite3_close(sqlite3* database)
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 11/14
12/12/11
11
Working with SQLite Databases
} SQL Statement Object
} An instance of “sqlite3_stmt” object represents a single SQL statement.
} To execute a SQL query, the query string (contained in a characterbased string) needs to be converted to a SQL statement object.
} Example
41
sqlite3_stmt
//query to get all records from the task tableconst char *sqlChar = “SELECT * from task;”;
//SQL statement object to represent the string quer ysqlite3_stmt* all_task_query;
Working with SQLite Database
} Method used to convert SQL query to SQL statement object
int sqlite3_prepare_v2( sqlite3* database, const char *sql ,int querysize, sqlite3_stmt** ppStatement,
const char **pzTail )
database, Reference to the database.sql , Character str ing that holds to SQL.querysize, Size of the string holding SQL. If the querysize argument is less
than zero, then sql is read up to the first null terminator.
ppStatement, Pointer to pointer to SQL Statement object.
pzTail , Pointer to unused portion of zSql.
} Example :
const char *sqlChar = “SELECT * from task;”;sqlite3_stmt* all_task_query;sqlite3_prepare_v2(database, sqlChar, -1, &all_task_query, NULL);
42
int sqlite3_prepare_v2( sqlite3* database, const char *sql ,int querysize,sqlite3_stmt** ppStatement,const char **pzTail )
Working with SQLite Databases
} Execute the SQL Statement on the database
int sqlite3_step(sqlite3_stmt* sqlstatement)
This method is used to execute a prepared query contained in the SQLstatement object.
If SQL statement being executed returns any data, then SQLITE_ROW is
returned, else SQLITE_DONE is returned when query has executedsuccessfully.Values may be accessed using the column access functions.
sqlite3_step() is called in a loop to retrieve the next row of data.
int, If return value is SQLITE_ROW, data can be read usingcolumn access methods.
sqlstatement, sqllite3_stmt object after being prepared.
43
int sqlite3_step(sqlite3_stmt* sqlstatement)
Working with SQLite Databases
} Execute the SQL Statement on the database
} Example:
44
const char *sqlChar = “SELECT * from task;”;
sqlite3_stmt* all_task_query;
int success = sqlite3_prepare_v2(database, sqlChar, -1,&all_task_query, NULL);
if (success == SQLITE_OK) {
// Step through the results - once for each row.
while (sqlite3_step(statement) == SQLI TE_ROW) {
//Read the record columns}
}
if (success == SQLITE_OK) {
int result = sqlite3_step(statement);
if ( result == SQLITE_DONE) {
//Query executed successfully
}
Query returns data Query does not return data
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 12/14
12/12/11
12
Working with SQLite Database
} Reading data from table columns
} Check the type of data stored in table column.
int, Returns one of the fol lowing
SQLITE_INTEGER,
SQLITE_FLOAT,
SQLITE_BLOB,
SQLITE_NULL,
SQLITE3_TEXT
sqlstatement, SQL statement object.iCol , Column index (starting from 0) for the column.
int sqlite3_column_type(sqlite3_stmt* sqlstatement, int iCol );
Working with SQLite Database
} Reading data from table columns
} Reading Strings or TEXT type data from column
} Reading Integer type data
}
Reading Floating point data
const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
int sqlite3_column_int(sqlite3_stmt*, int iCol);
sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
double sqlite3_column_double(sqlite3_stmt*, int iCol);
Working with SQLite Database
} Reading data from table columns
} Reading BLOB type data from column
} Functions that return the size of the blob in bytes
} Function to read the BLOB data
const void *sqlite3_column_blob(sqlite3_stmt*, int iCol );
int sqlite3_column_bytes(sqlite3_stmt*, int iCol );
int sqlite3_column_bytes16(sqlite3_stmt*, int iCol );
Working with SQLite Database
} De-allocate the SQL statement instance
} All SQL statement instances should be de-allocated before the
database can be closed.
} Function used to de-allocate SQL statement instances
sqlstatement, Pointer to SQL statement instance to be de-allocated.
int sqlite3_finalize(sqlite3_stmt* sqlstatement)
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 13/14
12/12/11
13
Working with SQLite Databases
} Example
} First Step : Assemble your SQL code in a string.
} Second Step : Create an SQL statement object.
} Third Step : Prepare the SQL statement object with the SQL code.
49
Working with SQLite Databases
} Example
} Fourth Step : Execute the Query
} Fifth Step (optional) : Read data from columns
50
Creating DB Helper Classes
Amit Gulati
Objective-C Data Objects
} Implementing Objective-C classes to hold database records.
} Project class
52
7/28/2019 15 Data Persistence
http://slidepdf.com/reader/full/15-data-persistence 14/14
12/12/11
14
Objective-C Data Objects
} Implementing Objective-C classes to hold database records.
} Task class
53
For More Information on SQLite
} Books
} References
} http://www.sqlite.org