iOS 資料庫工具類分享
基于 對 FMDB 架構的封裝,實作通過模型操作資料庫的功能,不需要手寫SQL語句,隻要傳入一個Model,架構會自動将Model内資料儲存到指定資料庫中, 并且會自動建立資料庫,自動建立模型對應的表。
項目位址
XWSqliteTool功能清單
- 根據 Model 動态建表
- 若 Model 内字段發生變化自動進行表結構遷移
- 傳入 Model 自動将 Model 内資料儲存到資料庫對應的表中
- 傳入主鍵值擷取 Model 模型資料
- 大資料儲存,傳入多個資料模型批量存儲
- 多線程支援,多線程操作資料庫需要使用 操作隊列 進行操作。
使用說明
- 導入
庫XWSqliteTool
- 使需要操作的模型遵循
協定,并實作XWXModelProtocol
協定方法指定表的主鍵。+(NSString *)primaryKey
1. 動态建表
//根據模型建表
- (void)testCreateTableFromClass {
[XWSqliteModelFMDBTool createTableFromClass:[XWPerson class] callBack:^(BOOL isSuccess) {
XCTAssertTrue(isSuccess);
}];
}
2. 模型字段改變自動進行表資料遷移
// 模型字段增加更新資料庫
- (void)testUpdateModelTable {
[XWSqliteModelFMDBTool updateTableFromCls:[XWPerson class] updateSqls:nil callBack:^(BOOL isSuccess) {
XCTAssert(isSuccess == 1);
}];
}
3. 自動儲存一個Model到資料庫 (自動建立資料庫,自動建表)
// 插入/更新 單條資料模型
- (void)testInsertOneObj {
[XWSqliteModelFMDBTool insertOrUpdateDataToSQLiteWithModel:[self demoPerson] isUpdateTable:YES callBack:^(BOOL isSuccess) {
XCTAssertTrue(isSuccess);
}];
}
4. 自動儲存 Model 數組到資料庫 (自動建立資料庫,自動建表)
// 插入/更新 多條資料模型
- (void)testInsertObjs {
[XWSqliteModelFMDBTool insertOrUpdateDataToSQLiteWithModels:[self demoPersons] isUpdateTable:YES callBack:^(BOOL isSuccess) {
XCTAssertTrue(isSuccess);
}];
}
5.傳入主鍵值擷取 Model 模型資料
// 查詢 XWPerson 表中 主鍵 為 4 的模型
- (void)testQuery {
[XWSqliteModelFMDBTool objectFromDatabaseWithPrimaryValue:4 modelCls:[XWPerson class] resultCallBack:^(XWPerson *obj) {
NSLog(@"name:%@",obj.name);
}];
}
6.多線程操作資料庫
首先如果項目中需要多線程異步操作資料庫,需要将對資料庫操作集中管理,使用
dispatch_queue_t
進行統一管理。 例如Demo所示:
//
// ViewController.m
// XWSqliteToolDemo
//
// Created by 邱學偉 on 2018/4/8.
// Copyright © 2018年 邱學偉. All rights reserved.
//
#import "ViewController.h"
#import "XWSqliteModelFMDBTool.h"
#import "XWPerson.h"
@interface ViewController ()
@property (nonatomic, strong) dispatch_queue_t databaseQueue;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.databaseQueue = dispatch_queue_create("com.company.app.database", 0);
for (int i = 0; i < 1000; i++) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
XWPerson *stu = [[XWPerson alloc] init];
stu.name = [NSString stringWithFormat:@"極客學偉_%d",i];
stu.sex = 1;
stu.uid = [NSString stringWithFormat:@"%d",i];
stu.height = 188;
stu.address = @"北京回龍觀";
dispatch_sync(self.databaseQueue, ^{
// do your database activity here
[XWSqliteModelFMDBTool insertOrUpdateDataToSQLiteWithModel:stu isUpdateTable:YES callBack:^(BOOL isSuccess) {
NSLog(@"儲存成功 %@, 線程 %@",stu.name,[NSThread currentThread]);
}];
});
});
}
}
@end
原文位址https://blog.csdn.net/qiuxuewei2012/article/details/80282784