`
sillycat
  • 浏览: 2551026 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

IOS7 App Development Essentials(1) Persistent Store

 
阅读更多

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 = <context>;
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 = <>;
USURL *myURL = <>;
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 = <>;
NSURL *newURL = <>;
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
>TARGETS ——> Build Phases —> Link Binary With Libraries ———> libsqlite3.dylib

Importing sqlite3.h and declaring the Database Reference
#import <UIKit/UIKit.h> #import <sqlite3.h>@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

分享到:
评论

相关推荐

    iOS 10 App Development Essentials

    iOS 10 App Development Essentials: Learn to Develop iOS 10 Apps with Xcode 8 and Swift 3 Author: Neil Smyth Length: 816 pages Edition: 1 Language: English Publisher: CreateSpace Independent Publishing...

    iOS 11 App Development Essentials Learn to Develop iOS 11 Apps with Xcode 9 epub

    iOS 11 App Development Essentials Learn to Develop iOS 11 Apps with Xcode 9 and Swift 4 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网搜索此书

    iOS 11 App Development Essentials Learn to Develop iOS 11 Apps with Xcode 9

    1. Xcode 9与iOS 11 SDK的安装和配置:在开发iOS 11应用之前,必须确保已经安装了最新版的Xcode 9和iOS 11软件开发工具包(SDK)。此外,还需要确认你的Mac是基于Intel或PowerPC架构的,这关系到能否顺利安装Xcode。...

    iOS 11 App Development Essentials Learn to Develop iOS 11 Apps with Xcode 9 mobi

    iOS 11 App Development Essentials Learn to Develop iOS 11 Apps with Xcode 9 and Swift 4 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网搜索此书

    iOS 8 App Development Essentials Source Code

    《iOS 8应用开发基础》源码解析 本资源包含了使用Xcode 6.3(Swift 1.2)编写的iOS 8应用程序开发的基础源码。这些源代码旨在帮助开发者深入理解iOS 8应用开发的基本概念和技术,通过实际操作来学习Swift语言以及...

    iOS7 App Development Essentials

    iOS7应用开发基础是针对苹果公司的移动操作系统iOS 7版本和集成开发环境Xcode 5的软件开发指南。本书从基础着手,为读者提供了一个从零开始学习iOS应用开发的完整路线图。由于本书特别提到了它是为了iOS 7和Xcode 5...

    iOS 10 App Development Essentials mobi

    iOS 10 App Development Essentials 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    iOS 9 App Development Essentials 无水印pdf

    iOS 9 App Development Essentials 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系...

    iOS 11 App Development Essentials Learn to Develop iOS 11 Apps with 无水印转化版pdf

    本书《iOS 11 App Development Essentials》旨在帮助读者掌握开发 iOS 11 应用所需的基本技能。它覆盖了从安装开发环境到构建应用的全过程,并深入介绍了 Swift 4 编程语言的基础知识。对于新接触 iOS 开发的人来说...

    iOS 11 App Development Essentials

    《iOS 11应用开发精华》是Neil Smyth所著的一本书,旨在指导开发者如何使用Swift语言和Xcode开发工具来开发适用于iOS 11的iPhone应用。本书涵盖了从基础概念到高级特性的广泛内容,适合初学者和已有一些iOS开发经验...

    iPhone iOS 4 App开发要点iPhone iOS 4 App Development Essentials

    本书概述了iPhone硬件和iOS 4的体系结构。提供了Objective-C编程的简介,然后深入研究了iPhone应用程序和用户界面的设计。

    iOS.8.App.Development.Essentials

    Title: iOS 8 App Development Essentials Author: Neil Smyth Length: 824 pages Edition: 1 Language: English Publisher: CreateSpace Independent Publishing Platform Publication Date: 2014-12-16 ISBN-10: ...

    iOS 8 App开发要点iOS 8 App Development Essentials

    介绍如何使用Xcode和Swift构建适用于iOS 8的应用程序。

    iOS 16 App Development Essentials – UIKit Edition

    本书旨在教授使用 iOS 16 SDK、UIKit、Xcode 14 和 Swift 编程语言创建 iOS 应用程序所需的技能。 本书从基础开始,概述了设置 iOS 开发环境所需的步骤。接下来,介绍了 iOS 16 的架构和 Swift 5.7 中的编程,然后...

    iPad iOS 4 App开发要点-Xcode 4版iPad iOS 4 App development Essentials - Xcode 4 Edition

    1. **安装Xcode**:首先需要从Mac App Store下载并安装最新版本的Xcode。 2. **注册开发者账号**:为了能够在设备上测试应用并最终提交到App Store,需要注册成为苹果开发者。 3. **创建项目**:打开Xcode后,选择...

    iOS.9.App.Development.Essentials

    iOS 9 App Development Essentials is latest edition of this popular book series and has now been fully updated for the iOS 9 SDK, Xcode 7 and the Swift 2 programming language. Beginning with the ...

    Ios 9 Game Development Essentials

    总结来说,《iOS 9 Game Development Essentials》这本书覆盖了从基础的 Swift 编程语言到高级的游戏开发技术,适合想要入门 iOS 游戏开发的读者。通过本书的学习,你将能够掌握使用 Swift 和 SpriteKit/SceneKit ...

    Android 4.2 App开发要点Android 4.2 App Development Essentials

    使用Eclipse IDE和Android 4.2 SDK的Android应用程序开发简介。 本书假定您具有Java编程经验。

Global site tag (gtag.js) - Google Analytics