>

简单易用的iOS数据库操作框架,来做本地数据库

- 编辑:澳门新葡亰平台游戏 -

简单易用的iOS数据库操作框架,来做本地数据库

选拔cocoapods引进MagicalRecord和YYModel库。源码和用法看github就足以了:MagicalRecord: MagicalRecord git YYModel: YYModel git

5: 留下的坑 :
 1、第贰个创建立模型型的时候的,模型放置的岗位在xocde文件夹的最上边的那一块,取下来之后又会并发找不到文件的动静,有待化解.

开创和数据库
[[JCDBManager sharedManager] createWithDBName:@"testDB.sqlite"];

这边列举八个实人体模型型HVWBoy要贯彻的情势:

4、点了一块儿的规定之后,将会油不过生那4个文本,然后大家在须求选择到Person模型的地点导入 #import "Person+CoreDataClass.h" .

剔除记录
BOOL result = [JCTestRecord deleteRecordsWithConditions:@{@"testEnumType":@(JCTestEnumTypeTwo)}];

result = [JCTestRecord deleteRecordsWithConditionalExpression:@"WHERE testEnumType < ?"
                                                    arguments:@[@(JCTestEnumTypeOne)]];

result = [JCTestRecord deleteAllRecords];

以上正是该框架现存的剧情,扶助sqlite超越二分一的增加和删除改查操作,对于或许出现的别样须求,还索要大家一块保驾护航。

NSManagedObject+Common.m

图片 1

询问记录
JCTestRecord *record = [JCTestRecord queryRecordWithPrimaryKeyValue:@"primaryKeyProperty2"];

NSArray *queryRecords = [JCTestRecord queryRecordsWithConditions:@{@"testEnumType":@(JCTestEnumTypeTwo)}];

queryRecords = [JCTestRecord queryRecordsWithConditionalExpression:@"WHERE testEnumType < ?"
                                                         arguments:@[@(JCTestEnumTypeTwo)]];

queryRecords = [JCTestRecord queryRecordsWithConditionalExpression:@"ORDER BY testEnumType DESC"
                                                         arguments:nil];

queryRecords = [JCTestRecord queryAllRecords];
#import "HVWBoy.h"#import "HVWGirl.h"@implementation HVWBoy// Insert code here to add functionality to your managed object subclass// 自定义的“主键”,为了插入的时候不造成数据“冗余”,因为每次插入数据是CoreData自己生成真正的主键的+ (NSArray *)primaryKeys { return @[@"pid"];}// 容器元素类,使用了NSManagedObject+Common,需要实现这个类似于YYModel中containerPropertyGenericClass的方法,用来指明容器属性中元素的类型+ (NSDictionary *)coreDataModelContainerPropertyGenericClass { return @{@"girlfriends" : [HVWGirl class]};}// 黑名单,因为YYModel并不能自动进行转换,需要先屏蔽容器类属性+ (NSArray *)modelPropertyBlacklist { return @[@"girlfriends"];}@end

3、 接下来是建立模型,建立模型也和在此以前的本子不一样,不是事先的法子建立模型了,建立模型的地点停放到了此处:

关门数据库
[[JCDBManager sharedManager] closeDB];

调用:ViewController

图7 扩大和询问代码。

删除表
[JCTestRecord dropTable];
@interface NSManagedObject + (NSArray *)getAllObjects:(NSManagedObjectContext *)context;+ deleteAllObjects:(NSManagedObjectContext *)context;+ (instancetype)getObjectWithPrimaryKeyPredicates:(NSArray *)predicates context:(NSManagedObjectContext *)context;+ deleteObjectWithPrimaryKeyPredicates:(NSArray *)predicates context:(NSManagedObject *)context;+ (instancetype)insertOrReplaceWithDictionary:(NSDictionary *)dict context:(NSManagedObjectContext *)context;+ (NSArray *)insertWithArray:(NSArray *)array context:(NSManagedObjectContext *)context;// 原NSManagedObject需要实现的方法+ (NSArray *)primaryKeys;+ (NSDictionary *)coreDataModelContainerPropertyGenericClass;@end

github   

查询表中著录条数
uint64_t count = [JCTestRecord countRecordsWithConditions:@{@"testEnumType":@(JCTestEnumTypeTwo)}];

count = [JCTestRecord countRecordsWithConditionalExpression:@"WHERE testEnumType < ?"
                                                  arguments:@[@(JCTestEnumTypeOne)]];

count = [JCTestRecord countAllRecords];

NSManagedObject+Common.h

6、然后大家就足以初阶对数码进行 增加和删除查改 的四项操作了. 小编用SB拖了4个按键,分别对应增加和删除查改。其余的切切实实上代码。

删除当前记录
result = [record deleteRecord];
  1. 在Entity Class中落到实处分类中要调用的办法"primaryKeys"用来钦定自定义主键,"coreDataModelContainerPropertyGenericClass"钦命容器属性中的成分类,modelPropertyBlacklist屏蔽relation的普通赋值。
  2. 读取json数据,分析成字典。
  3. 使用MagicalRecord创建DB Entity,再使用YYModel赋值。
  4. 利用runtime,探测出此Entity中的relation,并递归调用上一步的创立Entity和赋值逻辑。
  5. 存入数据库。

   那是本身的率先篇简书,记录的是有关在升级Xcode8今后,如何接纳 iOS 第三方 MagicalRecord 库的艺术,要是发掘别的的主题素材请直接留言恐怕关联小编邮箱: aaasss_6002@qq.com 。

图片 2

思路是:

1: 下载好之后,创设好叁个工程,不要勾选 Core Data,然后使用 cocoapods 下载安装好新型版本的 MagicalRecord

sql-stmt.png

#import "ViewController.h"#import "HVWBoy.h"#import "HVWGirl.h"#import "NSManagedObject+Common.h"@interface ViewController ()- readJsonAndSave:(UIButton *)sender;- readAllBoysFromDB:(UIButton *)sender;- cleanDBData:(UIButton *)sender;@end@implementation ViewController- viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. }- didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}- readJsonAndSave:(UIButton *)sender { NSString *json = @"{"data":[{"girlfriends":[{"pid":200,"name":"Judy"},{"pid":201,"name":"Summer"},{"pid":202,"name":"Sufia"}],"pid":100,"name":"John","nick":"Programer","age":25},{"girlfriends":[{"pid":203,"name":"Aoi"}],"pid":101,"name":"Peter","nick":"PM","age":30}]}"; NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:NULL]; // 在使用NSManagedObject+Common之前,需要手动先创建实例,再进行字典转模型,且不能处理容器属性 // NSManagedObjectContext *context = [NSManagedObjectContext MR_rootSavingContext]; // // for (NSDictionary *dic in [dataDic objectForKey:@"data"]) { // HVWBoy *boy = [HVWBoy MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"pid = %d", [[dic objectForKey:@"pid"] intValue]]]; // if  { // boy = [HVWBoy MR_createEntityInContext:context]; // } // // [boy yy_modelSetWithDictionary:dic]; // [context MR_saveToPersistentStoreAndWait]; // } // 使用NSManagedObject+Common之后 NSManagedObjectContext *context = [NSManagedObjectContext MR_rootSavingContext]; // 只需要调用一个方法,就可以自动从json转换到Core模型对象并存储 [HVWBoy insertWithArray:[dataDic objectForKey:@"data"] context:context]; NSLog(@"Save data into DB succeeded!");}- readAllBoysFromDB:(UIButton *)sender { // NSManagedObjectContext *context = [NSManagedObjectContext MR_defaultContext]; NSArray *boys = [HVWBoy MR_findAll]; if (!boys.count) { NSLog(@"No data in DB!"); return; } for (HVWBoy *boy in boys) { NSLog(@"boy --> pid:%lld, name:%@, age:%d, nick:%@", boy.pid, boy.name, boy.age, boy.nick); for (HVWGirl *girl in boy.girlfriends) { NSLog(@"%@'s girlfriend --> pid:%lld, name:%@", boy.name, girl.pid, girl.name); } }}- cleanDBData:(UIButton *)sender { NSArray *boys = [HVWBoy MR_findAll]; for (HVWBoy *boy in boys) { [boy MR_deleteEntity]; [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait]; } NSLog(@"Clean DB succeeded");}@end

7、扩张和询问

那套框架近日支撑以下数据库操作:

#import "NSManagedObject+Common.h"#import <objc/message.h>#import <objc/runtime.h>#define ENTITY_NAME NSStringFromClass([self class])#pragma clang diagnostic push#pragma clang diagnostic ignored "-Wincomplete-implementation"@implementation NSManagedObject #pragma clang diagnostric pop+ (NSArray *)getAllObjects:(NSManagedObjectContext *)context { return [self MR_findAllWithPredicate:nil inContext:context];}+ deleteAllObjects:(NSManagedObjectContext *)context { if  { return; } NSArray *objects = [self getAllObjects:context]; for (NSManagedObject *object in objects) { [object MR_deleteEntityInContext:context]; [context MR_saveToPersistentStoreAndWait]; }}+ (instancetype)getObjectWithPrimaryKeyPredicates:(NSArray *)predicates context:(NSManagedObjectContext *)context { if (!predicates || !context) { return nil; } NSMutableString *preStr = [NSMutableString string]; NSArray *primaryKeys = [self primaryKeys]; if (predicates.count != primaryKeys.count) { return nil; } for (int i=0; i<primaryKeys.count; i++) { NSString *predicateKey = primaryKeys[i]; NSObject *value = predicates[i]; if ([value isKindOfClass:[NSString class]]) { [preStr appendString:[NSString stringWithFormat:@" (%@ = "%@") ", predicateKey, value]]; } else { [preStr appendString:[NSString stringWithFormat:@"  ", predicateKey, value]]; } if (i != primaryKeys.count - 1) { [preStr appendString:@" AND "]; } } return [self MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:preStr] inContext:context];}+ deleteObjectWithPrimaryKeyPredicates:(NSArray *)predicates context:(NSManagedObjectContext *)context { NSManagedObject *object = [self getObjectWithPrimaryKeyPredicates:predicates context:context]; [object MR_deleteEntityInContext:context]; [context MR_saveToPersistentStoreAndWait];}+ (instancetype)insertOrReplaceWithDictionary:(NSDictionary *)dict context:(NSManagedObjectContext *)context { if (!dict || !context) { return nil; } NSMutableArray *predicates = [NSMutableArray array]; for (NSString *primaryKey in [self primaryKeys]) { [predicates addObject:[dict valueForKey:primaryKey]]; } NSManagedObject *object = [self getObjectWithPrimaryKeyPredicates:predicates context:context]; if  { object = [self MR_createEntityInContext:context]; } [context MR_saveToPersistentStoreAndWait]; [object yy_modelSetWithDictionary:dict]; [object handleRelationsWithDictionary:dict context:context]; [context MR_saveToPersistentStoreAndWait]; return object;}+ (NSArray *)insertWithArray:(NSArray *)array context:(NSManagedObjectContext *)context { if (!array || !context) { return nil; } NSMutableArray *result = [NSMutableArray arrayWithCapacity:array.count]; for (NSDictionary *dict in array) { NSManagedObject *object = [self insertOrReplaceWithDictionary:dict context:context]; [result addObject:object]; } return result;}// 处理容器类属性,传入的dictionary中的NSArray,NSDictionary- handleRelationsWithDictionary:(NSDictionary *)dict context:(NSManagedObjectContext *)context { [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSObject *obj, BOOL * _Nonnull stop) { if ([obj isKindOfClass:[NSArray class]]) { objc_property_t property = class_getProperty([self class], key.UTF8String); if ([[self class] respondsToSelector:@selector(coreDataModelContainerPropertyGenericClass)]) { NSDictionary *classDict = [[self class] coreDataModelContainerPropertyGenericClass]; NSString *key = [NSString stringWithUTF8String:property_getName]; Class c = [classDict objectForKey:key]; NSArray *savedRelationObjects = [c insertWithArray:(NSArray *)obj context:context]; [self setValue:[NSSet setWithArray:savedRelationObjects] forKey:key]; [context MR_saveToPersistentStoreAndWait]; } } else if ([obj isKindOfClass:[NSDictionary class]]) { objc_property_t property = class_getProperty([self class], key.UTF8String); NSString *key = [NSString stringWithUTF8String:property_getName]; unsigned int count = 0; objc_property_attribute_t *attrs = property_copyAttributeList(property, &count); for (int i=0; i<count; i++) { objc_property_attribute_t attr = attrs[i]; NSString *attrName = [NSString stringWithUTF8String:attr.name]; if ([@"T" isEqualToString:attrName]) { // 属性类名key是"T" NSString *className = [NSString stringWithUTF8String:attr.value]; // 这是带有"@"和双引号的类名字符串,例如@"User" className = [className stringByReplacingOccurrencesOfString:@"@" withString:@""]; className = [className stringByReplacingOccurrencesOfString:@""" withString:@""]; Class c = NSClassFromString(className); NSManagedObject *savedRelationObject = [c insertOrReplaceWithDictionary:(NSDictionary *)obj context:context]; [self setValue:savedRelationObject forKey:key]; [context MR_saveToPersistentStoreAndWait]; break; } } } }];}@end

图片 3

安插或代表当前记下
JCTestRecord *record = [[JCTestRecord alloc] init];
record.testPrimaryKey = [NSString stringWithFormat:@"primaryKeyProperty%@", @(index + 1)];
record.testIgnore = @"ignoreProperty";
record.testMutableString = [[NSMutableString alloc] initWithString:@"mutableStringProperty"];
record.testNumber = @(6.20);
record.testDecimalNumber = [[NSDecimalNumber alloc] initWithString:@"2016"];
record.testDate = [NSDate date];
record.testData = [@"dataProperty" dataUsingEncoding:NSUTF8StringEncoding];
record.testMutableData = [NSMutableData dataWithData:[@"mutableDataProperty" dataUsingEncoding:NSUTF8StringEncoding]];

record.testBOOL = YES;
record.testShort = 6;
record.testInt = 20;
record.testLong = 20160620;
record.testInteger = index + 1;
record.testEnumType = (index + 1) % 3;
record.testInt64 = (index + 1)*24*3600;
record.testUInteger = 201606;
record.testFloat = 10.5;
record.testCGFloat = 1.26;
record.testDouble = 10.52;
record.testTimeInterval = 978307200.0;
record.testLongInt = 10000010;
record.testLongLongInt = 1000000110;
record.testUnsignedLongLongInt = 100000000111;

BOOL result = [record updateRecord];

Demo: MagicalRecord+YYModel

5、这样做了后来,还恐怕有一个操作,正是在 AppDelegate.m 文件的 - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions 方法里面加多数据库存款和储蓄的职分提出增添以下全部代码,不然在支配台会有部分竟然的出口。

前不久稍闲,静下心来回看了这几年的付出工作,开采沉淀到文字里的东西太少,于是封装了多少个iOS开辟进度中时时要用到的互连网诉求、文件下载、数据库操作等框架,与大家享用一下。这里大概介绍下基于 FMDB 和 SQLite 的一套轻量级数据库操作框架,源码请点击这里 JCDB 。

2、假如一贯从 Github 上收取来 MagicalRecord  那么会有文件找不到的报错,不精通什么样消除。

询问记录的连带字段
NSArray *queryColumns = [JCTestRecord queryColumns:@[@"testPrimaryKey", @"testDate"]
                             conditionalExpression:@"WHERE testEnumType < ? ORDER BY testInteger DESC"
                                         arguments:@[@(JCTestEnumTypeOne)]];

2 建立Data Model

创建表
[JCTestRecord createTable];

图片 4

更新当前记下字段值
result = [record updateRecordColumns:@[@"testBOOL", @"testDate", @"testNumber"]
                              values:@[@(NO), [NSDate dateWithTimeIntervalSince1970:9], @(6.22)]];

图片 5

  1. 数据库表的 CREATE、DROP 和 ALERT。
  2. 数据库记录的连锁询问 SELECT。
  3. 数据库记录的 INSERT、REPLACE、UPDATE 和 DELETE。

[[NSManagedObjectContextMR_defaultContext]MR_saveToPersistentStoreAndWait]; 

加多表字段
[JCTestRecord alterTableWithColumn:@"testUnsignedLongLongInt"];

 2、建模Person,并增多属性。 首先选用TestModel ,然后点击坐下角的 Add Entity ,再修改名字成Person,再分别增添Person的八个属性,name , work ,age ,并给它们的type设置成string 、string 、integer 16,别的重视看第5点(箭头指向的地方) 这么些是要安装成OC语言的,当然假若是swift语言就另说,那是和Xcode8在此之前的本子分裂的地方.

图3 建立模型的地点

图5 早先化数据库路线

3: 接下来,我们要求树立模型必要的模型, 做三个只要,这里建贰个Person模型,属性有3个,name,age,work。然后进行相应的增加和删除查改操作.

图8 删除和改造

ps:这里解释下怎么不去github直接下载然后放置工程,因为直接下载后拉入新的工程,会合世文件找不到的图景,作者也尝试过非常久其余艺术,个中一个要贰个个 把 (#import )把文件的路径都改掉,那样很麻烦,所以平素用cocoapods比较便于,能直接集成好,假诺您正是麻烦,能够团结改。

4: 稍稍总计了一晃 ,用 MagicalRecord 来作为本土数据仓库储存款和储蓄是很实惠,制止了写过多布署,只供给几行代码就可以达成项目的须要,其它表明一下,仅有在读取数据的时候是无需做保留操作的,其它的对数据库的操作是都亟需在成就的时候,使用上边那行代码来展锦州存。

最后在 Github 留下 Demo 地址 .

率先先贴出  MagicalRecord 库的github地址,顺便感激有个那样好的库。

2: 为项目增多 CoreData.FrameWork。(点工程根节点,然后依次  Targets > Build Phases > Link Binary With Libraries > + > CoreData.framework > 增加 ),然后在文书需求动用到 MagicalRecord 库的地点: #import <MagicalRecord/MagicalRecord.h> 

图片 6

图片 7

图4 建构好模型的地点

图片 8

图片 9

1

图2 建立 Person 模型

  1、创设贰个Data Model, 名字自取,作者这里名字是 TestModel,然后 就能够多了2这么些文件。

8、删除和修改.

本文由java编程发布,转载请注明来源:简单易用的iOS数据库操作框架,来做本地数据库