使用MagicalRecord对CoreData的二次封装进行数据库操作
使用cocoapods引入MagicalRecord和YYModel库。
源码和用法看github就可以了:
MagicalRecord: MagicalRecord git
YYModel: YYModel git
Demo: MagicalRecord+YYModel
使用YYModel自动转换json数据为CoreData模型对象,YYModel不支持CoreData模型的转换,这里利用runtime写了一个分类"NSManagedObject+Common",用以支持CoreData的转换。
思路是:
- 在Entity Class中实现分类中要调用的方法"primaryKeys"用来指定自定义主键,"coreDataModelContainerPropertyGenericClass"指定容器属性(relation)中的元素类,modelPropertyBlacklist屏蔽relation的普通赋值。
- 读取json数据,解析成字典。
- 使用MagicalRecord创建DB Entity,再使用YYModel赋值。
- 使用runtime,探测出此Entity中的relation,并递归调用上一步的创建Entity和赋值逻辑。
- 存入数据库。
NSManagedObject+Common.h
@interface NSManagedObject (Common)
+ (NSArray *)getAllObjects:(NSManagedObjectContext *)context;
+ (void)deleteAllObjects:(NSManagedObjectContext *)context;
+ (instancetype)getObjectWithPrimaryKeyPredicates:(NSArray *)predicates context:(NSManagedObjectContext *)context;
+ (void)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
NSManagedObject+Common.m
#import "NSManagedObject+Common.h"
#import
#import
#define ENTITY_NAME NSStringFromClass([self class])
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wincomplete-implementation"
@implementation NSManagedObject (Common)
#pragma clang diagnostric pop
+ (NSArray *)getAllObjects:(NSManagedObjectContext *)context {
return [self MR_findAllWithPredicate:nil inContext:context];
}
+ (void)deleteAllObjects:(NSManagedObjectContext *)context {
if (!context) {
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
这里列举一个实体模型HVWBoy要实现的方法:
#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
调用:
ViewController
#import "ViewController.h"
#import "HVWBoy.h"
#import "HVWGirl.h"
#import "NSManagedObject+Common.h"
@interface ViewController ()
- (IBAction)readJsonAndSave:(UIButton *)sender;
- (IBAction)readAllBoysFromDB:(UIButton *)sender;
- (IBAction)cleanDBData:(UIButton *)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)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) {
// 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!");
}
- (IBAction)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);
}
}
}
- (IBAction)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