FMDBHelper 1.1.0

FMDBHelper 1.1.0

测试已测试
语言语言 Obj-CObjective C
许可 MIT
发布上次发布2018年9月

lijingcheng 维护。



FMDBHelper

CI Status Version License Platform

安装

FMDBHelper 可以通过 CocoaPods 使用。要安装它,只需将以下行添加到您的 Podfile 中

pod 'FMDBHelper', '1.1.0'

性能

支持 sqlite rw。

使用

  • #import "FMDBHelper.h" 添加到您的 prefix.pch 中
  • 然后,运行 [FMDBHelper setDataBaseName:@"demo.db"];

示例

如果你有一个这样的表格

user (
id text PRIMARY KEY,
name text,
age integer,
birthday text,
dept text,
dogs text
)

或者有这样一个JSON

{
"id": "a1b2c3d4e5",
"username": "李京城",
"age": 32,
"birthday": "1984/3/28",
"dept":{
"id": "f6g7h8i9j0",
"name": "dev",
"manager": "X"
},
"dogs":[{
"id": "0x0x0x0x",
"name": "ahuang",
"age": "15"
}, {
"id": "1x1x1x1x",
"name": "xhei",
"age": "6"
}
],
"nums":[
123,
234
]
}

创建一个模型类并声明属性,属性名称必须与数据库表中的字段名称一致,但不需要与JSON键一致。

//User.h
@interface User : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *birthday;
@property (nonatomic, strong) Dept *dept;
@property (nonatomic, copy) NSArray<Dog *> *dogs;
@property (nonatomic, copy) NSArray<NSNumber *> *nums;

@end

//User.m
@implementation User

// if the property name and the JSON keys is not the same key, you need to overwrite this method.
- (NSDictionary *)mapping {
return @{ @"username": @"name" };
}

// if the property type is a custom class, you need to overwrite this method.
- (NSDictionary *)objectPropertys {
return @{ @"dept": [Dept class] };
}

// If the property type is a NSArray<...>, and property type is a custom class, you need to overwrite this method.
- (NSDictionary *)genericForArray {
return @{ @"dogs": [Dog class] };
}

// if the model class name and the table name is different, you need to overwrite this method
+ (NSString *)tableName {
return @"sys_user";
}

@end

读取JSON并插入到表中。

NSString *path = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"json"];
NSDictionary *keyValues = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:NSJSONReadingMutableLeaves error:nil];

User *user = [[User alloc] initWithDictionary:keyValues];

[FMDBHelper insertObject:user];

从表中查询数据并初始化模型对象

NSDictionary *result = [FMDBHelper queryById:@"a1b2c3d4e5" from:[User tableName]];

User *user = [[User alloc] initWithDictionary:result];

NSLog(@"%@, %@, %ld, %@", user.ID, user.name, (long)user.age, user.birthday);
NSLog(@"%@, %@, %@", user.dept.ID, user.dept.name, user.dept.manager);

NSArray<Dog *> *dogs = user.dogs;

[dogs enumerateObjectsUsingBlock:^(Dog * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@,%@,%ld", obj.ID, obj.name, obj.age);
}];

更多用法请参考测试案例。

作者

李京城

许可证

FMDBHelper遵循MIT许可证。更多信息请参阅LICENSE文件。