一、配置FMDB环境
1、安装FMDB
如何安装FMDB就不细说了,可以手动拖,也可以用cocoapods。手动拖的时候要注意,xcode6及以后版本,sql lib要从系统盘里拷出来。本文使用cocopods,文章结尾提供配置好的文件使用。
2、其他配置
在info.plist文件中,添加Application supports iTunes file sharing 并将其属性设为YES,其目的是为了在调试的时候可以从机器中拷出db文件进行对照。如下图:
Screen Shot 2015-12-07 at 19.07.21.png
设置好plist后,使用db工具创建db文件,可以使用sqlite pro或firefox的插件,创建一个名为person_info的表,在其中加上name、age两项。然后将其保存为test.db。
具体如图:
Screen Shot 2015-12-07 at 19.18.16.png
配置好test.db后,将其拖入工程文件,add to targets记得勾上第一项。这时的目录如图:
Screen Shot 2015-12-07 at 19.24.34.png
好了,下面可以愉快的写代码了。
二、代码部分
用storyboard拖好控件并连线,如下图:
第一个controller用来保存数据,第二个controller用来显示保存的数据。
接下来可以写db部分了,新建一个NSObject类,命名为DBOperation,导入FMDB.h并初始化,
DBOperation.h
#import <Foundation/Foundation.h>
#import <FMDB.h>
@interface DBOperation : NSObject
@property (nonatomic, strong) FMDatabaseQueue *dbQueue;
//获取db操作实例
+ (instancetype)getDBOperationInstance;
@end
DBOperation.m
#import "DBOperation.h"
@implementation DBOperation
//获取db操作实例
+ (instancetype)getDBOperationInstance
{
static DBOperation *dbOperation;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dbOperation = [[DBOperation alloc] initWithDataBase];
});
return dbOperation;
}
- (id)initWithDataBase {
NSString *dbPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:dbPath]) {
NSString *pathFrom = [[NSBundle mainBundle] pathForResource:@"test.db" ofType:nil];
[fileManager copyItemAtPath:pathFrom toPath:dbPath error:nil];
}
self.dbQueue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
return self;
}
@end
新建一个Person Model,用于处理name与age
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
接下来,在DBOperation中增加插入数据方法与查询数据方法:
- (void)insertDataWithModel:(Person *)person
{
[self.dbQueue inDatabase:^(FMDatabase *db) {
NSString *sql = @"insert into person_info (name, age) values (?, ?);";
//注意这里要插入nsnumbr类型
[db executeUpdate:sql, person.name, [NSNumber numberWithInteger:person.age]];
}];
}
- (NSMutableArray *)selectDataFromDataBase
{
NSMutableArray *persons = [NSMutableArray array];
[self.dbQueue inDatabase:^(FMDatabase *db) {
NSString *sql = @"select * from person_info";
FMResultSet *result = [db executeQuery:sql];
while ([result next]) {
@autoreleasepool {
Person *person = [Person new];
person.name = [result stringForColumn:@"name"];
person.age = [result intForColumn:@"age"];
[persons addObject:person];
}
}
}];
return persons;
}
'''
这里就只写这两个sql了,对于sql不太掌握的,可以先花点时间把https://www.codecademy.com/learn 上的learn sql敲完,然后照着sql cookbook 敲到200页,做iOS开发基本上就够用了。
在ViewController中的save Action调用insert function:
'''
- (IBAction)saveAction:(id)sender {
Person *person = [Person new];
person.name = self.nameField.text;
person.age = self.ageField.text.integerValue;
[[DBOperation getDBOperationInstance] insertDataWithModel:person];
self.nameField.text = @"";
self.ageField.text = @"";
}
在SecondTableViewController中进行查询,此时SecondTableViewController.m如下:
#import "SecondTableViewController.h"
#import "DBOperation.h"
#import "Person.h"
@interface SecondTableViewController ()
@property (nonatomic, strong) NSArray *persons;
@end
@implementation SecondTableViewController
static NSString *const kCellIdentifier = @"CellIdntifier";
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"SQL Data";
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kCellIdentifier];
[self readDataFromDB];
}
- (void)readDataFromDB
{
DBOperation *dbOperation = [DBOperation getDBOperationInstance];
self.persons = [NSArray arrayWithArray:[dbOperation selectDataFromDataBase]];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.persons.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
Person *person = self.persons[indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"name:%@, age:%ld", person.name, (long)person.age];
return cell;
}
@end
接下来,我们一次插入三组数据name:Peter, age:22 ; name:Jack, age:20; name:Tom, age:24。
Simulator Screen Shot Dec 7, 2015, 20.58.46.png此时进入 SecondTableViewController应该看到下图所示:
Simulator Screen Shot Dec 7, 2015, 20.58.50.png
![Upload Simulator Screen Shot Dec 7, 2015, 20.58.50.png failed. Please try again.]
推出程序,然后我们打开itunes把test.db导出来验证一下:
Screen Shot 2015-12-07 at 21.04.52.png Screen Shot 2015-12-07 at 21.05.31.png
相关代码:链接: http://pan.baidu.com/s/1jHn7zl8 密码: nv5j
下一节介绍如何更新db蛤。
网友评论