---
title: "IOS7 App Development Essentials(1) Persistent Store "
author: "sillycat"
date: "2014-03-05T05:54:45Z"
tags: []
categories: ["移动开发"]
slug: "ios7-app-development-essentials-1-persistent-store"
draft: false
lastmod: "2014-03-05T05:54:45Z"
id: 2025652
url: "https://sillycat.iteye.com/blog/2025652"
---

IOS7 App Development Essentials(1) Persistent Store 

**1. Introduction**   
**Store Types and Behaviors**  
XML, atomic, SQLite, in-memory store.  
NSBinaryStoreType — build-in atomic store.

The XML store is not available on iOS.

**SQLite Store**  
Core Data provides a way to control sync behavior in SQLite using 2 independent pragmas.  
PRAGMA synchronous FULL 2/ NORMAL 1 / OFF 0  
PRAGMA fullfsync 1/0

NSPersistentStoreCoordinator  
NSPersistentStore

**2. Using Persistent Stores**  
**Creating and Accessing a Store**  
XML store fragment

NSManagedObjectContext \*moc = &lt;context&gt;;  
NSPersistentStoreCoordinator \*psc = \[moc persistentStoreCoordinator];  
NSError \*error = nil;  
NSDictionary \*option =   
     \[NSDictionary dictionaryWithObject: \[NSNumber numberWithBool:1]  
                              forKey:NSReadOnlyPersistentStoreOption];

NSPersistentStore \*roStore =  
     [psc addPersistentStoreWithType:NSXMLStoreType  
                    configuration:nil URL:url  
                    options:options error:&error];

Get a store from URL

NSPersistentStoreCoordinator \*psc = &lt;&gt;;  
USURL \*myURL = &lt;&gt;;  
NSPersistentStore \*myStore = \[psc persistentStoreForURL:myURL];  
NSFetchRequest \*request = \[\[NSFetchRequest alloc] init];  
\[request setAffectedStores: \[NSArray arrayWithObject: myStore ]];

**Changing a Store’s Type and Location**  
NSPersistentStoreCoordinator \*psc = \[aManagedObjectContext persistentStoreCoordinator];  
NSURL \*oldURL = &lt;&gt;;  
NSURL \*newURL = &lt;&gt;;  
NSError \*error = nil;

NSPersistentStore \*xmlStore = \[psc persistentStoreForURL:oldURL];  
NSPersistentStore \*sqLiteStore = [psc migratePersistentStore: xmlStore  
                    otURL:newURL  
                    options:nil  
                    withType:NSSQLiteStoreType  
                    error:&error];

**2. Example CoreDataBooks**  
CoreData.framework

**3. Solutions Iphone Sqlite VS. Core Data**  
**SQLite directly**  
Relational Database System  
Protential for cross platform  
Many early iPhone database example  
Object-c Wrappers FMDB

**Core Data**  
Store in binary or SQLite storage format  
Serialize Objects  
Higher level  
Not a RDBMS

**4. Directly Using SQLite**  
**Link the lib**  
&gt;TARGETS ——&gt; Build Phases —&gt; Link Binary With Libraries ———&gt; libsqlite3.dylib

**Importing sqlite3.h and declaring the Database Reference**  
#import &lt;UIKit/UIKit.h&gt; #import &lt;sqlite3.h&gt;@interface easylocationViewController : UIViewController@property (strong, nonatomic) NSString \*databasePath; @property (nonatomic) sqlite3 \*contactDB;  
@end

**Designing the User Interface**  
buttons: find and save  
labels: name, address and phone, status  
text: name, address, phone

ctrl + click to link all the input text boxes and one label ’status’ to Interface class, create some outlets.  
ctrl + click to link buttons to Interface class, create some actions.

@property (strong, nonatomic) IBOutletUITextField \*name; @property (strong, nonatomic) IBOutletUITextField \*address; @property (strong, nonatomic) IBOutletUITextField \*phone; @property (strong, nonatomic) IBOutletUILabel \*status; - (IBAction)saveData:(id)sender;  
\- (IBAction)findContact:(id)sender;

**Creating the Database and Table**  
\- (void)viewDidLoad {    \[superviewDidLoad];    NSString \*docsDir;    NSArray \*dirPaths;        // Get the documents directory    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);        docsDir = dirPaths\[0];        // Build the path to the database file    \_databasePath = \[\[NSStringalloc]                     initWithString: \[docsDir stringByAppendingPathComponent:@"contacts.db"]];        NSFileManager \*filemgr = \[NSFileManagerdefaultManager];        if (\[filemgr fileExistsAtPath: \_databasePath ] == NO)    {        constchar \*dbpath = \[\_databasePathUTF8String];                if (sqlite3\_open(dbpath, &\_contactDB) == SQLITE\_OK)        {            char \*errMsg;            constchar \*sql\_stmt =            "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";                        if (sqlite3\_exec(\_contactDB, sql\_stmt, NULL, NULL, &errMsg) != SQLITE\_OK)            {                \_status.text = @"Failed to create table";            }            sqlite3\_close(\_contactDB);        } else {            \_status.text = @"Failed to open/create database";        }    } }

**Implementing the Code to Save Data to the SQLite Database**  
\- (IBAction)saveData:(UIButton \*)sender {    sqlite3\_stmt    \*statement;    constchar \*dbpath = \[\_databasePathUTF8String];        if (sqlite3\_open(dbpath, &\_contactDB) == SQLITE\_OK)    {                NSString \*insertSQL = \[NSStringstringWithFormat:                               @"INSERT INTO CONTACTS (name, address, phone) VALUES (\\"%@\\", \\"%@\\", \\"%@\\")", self.name.text, self.address.text, self.phone.text];                constchar \*insert\_stmt = \[insertSQL UTF8String];                sqlite3\_prepare\_v2(\_contactDB, insert\_stmt, -1, &statement, NULL);                if (sqlite3\_step(statement) == SQLITE\_DONE)        {            self.status.text = @"Contact added";            self.name.text = @"";            self.address.text = @"";            self.phone.text = @"";        } else {            self.status.text = @"Failed to add contact";        }        sqlite3\_finalize(statement);        sqlite3\_close(\_contactDB);    }  
}

**Implementing Code to Extract Data from the SQLite Database**  
\- (IBAction)findContact:(UIButton \*)sender {    constchar \*dbpath = \[\_databasePathUTF8String];    sqlite3\_stmt    \*statement;        if (sqlite3\_open(dbpath, &\_contactDB) == SQLITE\_OK)    {        NSString \*querySQL = \[NSStringstringWithFormat: @"SELECT address, phone FROM contacts WHERE name=\\"%@\\"", \_name.text];                constchar \*query\_stmt = \[querySQL UTF8String];                if (sqlite3\_prepare\_v2(\_contactDB, query\_stmt, -1, &statement, NULL) == SQLITE\_OK)        {            if (sqlite3\_step(statement) == SQLITE\_ROW)            {                NSString \*addressField = \[\[NSStringalloc]                                          initWithUTF8String:                                          (constchar \*) sqlite3\_column\_text(statement, 0)];                \_address.text = addressField;                NSString \*phoneField = \[\[NSStringalloc]                                        initWithUTF8String:                                        (constchar \*)sqlite3\_column\_text(statement, 1)];                \_phone.text = phoneField;                \_status.text = @"Match found";            } else {                \_status.text = @"Match not found";                \_address.text = @"";                \_phone.text = @"";            }            sqlite3\_finalize(statement);        }        sqlite3\_close(\_contactDB);    }  
}

**One Tips for Text Input box**  
Add this in the View Controller  
\- (void)touchesBegan:(NSSet \*)touches withEvent:(UIEvent \*)event{     NSLog(@"touchesBegan:withEvent:");     \[self.viewendEditing:YES];     \[supertouchesBegan:touches withEvent:event];  
}

**References:**  
http://sillycat.iteye.com/blog/1837717  
https://developer.apple.com/library/ios/search/?q=SQLite

sample code  
https://developer.apple.com/library/ios/samplecode/CoreDataBooks/Introduction/Intro.html

Directly use SQLite  
http://www.techotopia.com/index.php/An\_Example\_SQLite\_based\_iOS\_6\_iPhone\_Application  
http://stackoverflow.com/questions/4314866/what-is-the-difference-between-libsqlite3-dylib-and-libsqlite3-0-dylib  
http://stackoverflow.com/questions/989558/best-practices-for-in-app-database-migration-for-sqlite  
http://www.sqlite.org/lang\_altertable.html

Core Data  
http://www.techotopia.com/index.php/Working\_with\_iOS\_6\_iPhone\_Databases\_using\_Core\_Data  
http://www.techotopia.com/index.php/An\_iOS\_6\_iPhone\_Core\_Data\_Tutorial  
http://cases.azoft.com/database-migration-ios-applications/

text field editor  
http://mobile.tutsplus.com/tutorials/iphone/ios-sdk-uitextfield-uitextfielddelegate/  
http://www.techotopia.com/index.php/IOS\_7\_App\_Development\_Essentials