一、配置FMDB環(huán)境
1、安裝FMDB
如何安裝FMDB就不細說了,可以手動拖,也可以用cocoapods。手動拖的時候要注意,xcode6及以后版本,sql lib要從系統(tǒng)盤里拷出來。本文使用cocopods,文章結(jié)尾提供配置好的文件使用。
2、其他配置
在info.plist文件中,添加Application supports iTunes file sharing 并將其屬性設(shè)為YES,其目的是為了在調(diào)試的時候可以從機器中拷出db文件進行對照。如下圖:

設(shè)置好plist后,使用db工具創(chuàng)建db文件,可以使用sqlite pro或firefox的插件,創(chuàng)建一個名為person_info的表,在其中加上name、age兩項。然后將其保存為test.db。
具體如圖:

配置好test.db后,將其拖入工程文件,add to targets記得勾上第一項。這時的目錄如圖:

好了,下面可以愉快的寫代碼了。
二、代碼部分
用storyboard拖好控件并連線,如下圖:

第一個controller用來保存數(shù)據(jù),第二個controller用來顯示保存的數(shù)據(jù)。
接下來可以寫db部分了,新建一個NSObject類,命名為DBOperation,導(dǎo)入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中增加插入數(shù)據(jù)方法與查詢數(shù)據(jù)方法:
- (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開發(fā)基本上就夠用了。
在ViewController中的save Action調(diào)用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
接下來,我們一次插入三組數(shù)據(jù)name:Peter, age:22 ; name:Jack, age:20; name:Tom, age:24。

此時進入 SecondTableViewController應(yīng)該看到下圖所示:

![Upload Simulator Screen Shot Dec 7, 2015, 20.58.50.png failed. Please try again.]
推出程序,然后我們打開itunes把test.db導(dǎo)出來驗證一下:


相關(guān)代碼:鏈接: http://pan.baidu.com/s/1jHn7zl8 密碼: nv5j
下一節(jié)介紹如何更新db蛤。