Xcode8, MagicalRecord使用

MagicalRecord 库的github地址
github https://github.com/magicalpanda/MagicalRecord

1、用cocoa pods下载

pod 'MagicalRecord'

2、为项目添加 CoreData.FrameWork

(点工程根节点,然后依次 Targets > Build Phases > Link Binary With Libraries > + > CoreData.framework > 添加 ),
然后在文件需要使用到 MagicalRecord 库的地方:

#import  

3、建立模型

做一个比方,这里建一个Person模型,属性有3个,name,age,work。然后进行相应的增删查改操作.

  • 建立一个Data Model, 名字自取,我这里名字是 TestModel,然后 就会多了箭头2所指的这个文件。


    Xcode8, MagicalRecord使用_第1张图片
    奋斗的七月
  • 建立模型Person,并添加属性。 首先选择TestModel ,然后点击坐下角的 Add Entity ,再修改成Person,再分别添加Person的三个属性,name , work ,age ,并给它们的type设置成string 、string 、integer 16,另外着重看第5点(箭头指向的地方) 这个是要设置成OC语言的,当然如果是swift语言就另说,这是和Xcode8之前的版本不同的地方.


    Xcode8, MagicalRecord使用_第2张图片
    奋斗的七月
  • 接下来是建模,建模也和之前的版本不同,不是之前的方法建模了,建模的地方放置到了这里:


    Xcode8, MagicalRecord使用_第3张图片
    奋斗的七月
  • 点了一路的确定之后,将会出现这4个文件,然后我们在需要使用到Person模型的地方导入 #import "Person+CoreDataClass.h" .


    Xcode8, MagicalRecord使用_第4张图片
    奋斗的七月

4、MagicalRecord使用

在 AppDelegate.m 文件的 - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions 初始化

// 对Magical Record的初始化
    [MagicalRecord setupCoreDataStackWithStoreNamed:@"YJH.sqlite"];
添加功能
// 创建记录
- (void)createData {
     Person *person = [Person MR_createEntity];
     person.firstName = @"张";
     person.lastName = @"三";
     person.age = @25;
     [[NSManagedObjectContext MR_defaultContext]     MR_saveToPersistentStoreAndWait];
}
查询功能
// 查询记录
- (void)findData {
     // 查找数据库中的所有数据
     NSArray *person = [Person MR_findAll];
     // 查找所有的Person并按照firstName排序
     NSArray *personSorted = [Person MR_findAllSortedBy:@"firstName" ascending:YES];
     // 查找所有的age属性为25的Person记录
     NSArray *personAgeEqual25 = [Person MR_findByAttribute:@"age" withValue:[NSNumber numberWithInt:25]];
     // 查找数据库中的第一条记录
     Person *personFirst = [Person MR_findFirst];

     NSLog(@"%@  %@  %@  %@", person, personSorted, personAgeEqual25, personFirst);

     // 查找数据库中的第一条记录的全名
     personFirst = [Person MR_findFirst];
     NSLog(@"personName:%@%@", personFirst.firstName, personFirst.lastName);
}
修改功能
// 更新记录
- (void)updateData {
     NSArray *personArr = [Person MR_findByAttribute:@"age" withValue:    [NSNumber numberWithInt:25]];
     NSEnumerator *keyEnumerator;
     keyEnumerator = [personArr objectEnumerator];
     Person *person;
     while (person = [keyEnumerator nextObject]) {
          person.firstName = @"李";
     }

     for (Person *person in personArr) {
          person.lastName = @"四";
     }

     [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
}
删除功能
// 删除记录
- (void)deleteData {
     NSArray *personArr = [Person MR_findByAttribute:@"age" withValue:   [NSNumber numberWithInt:25]];
     for (Person *person in personArr) {
         [person MR_deleteEntity];
     }

     [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
}

5、总结

稍稍总结了一下 ,用 MagicalRecord 来作为本地数据库存储是很方便,避免了写很多配置,只需要几行代码就能够完成项目的需求,另外标注一下,只有在读取数据的时候是不需要做保存操作的,其它的对数据库的操作是都需要在完成的时候,使用下面这行代码来进行保存。

[[NSManagedObjectContextMR_defaultContext]MR_saveToPersistentStoreAndWait]; 

3个小技巧

启动时MR_mergedObjectModelFromMainBundle方法报错

Core Data的模型有版本的概念,有可能在你Magical Record第一次初始化完成以后,你又更改了模型文件,导致Core Data去合并模型报错。解决办法很简单,点击菜单中的Project->Clean即可。

项目使用ARC后,编译Magical Record不通过

点击项目 -> Build Phases -> Compile Sources中, 双击报错的class文件, 编辑Compiler Flags加入 -fno-objc-arc。

不想使用MR_前缀

只需要在*-Prefix.pch文件中添加一句#define MR_SHORTHAND即可,注意这句要在#import “CoreData+MagicalRecord.h”之前。

项目实例

1.新建并存储

#pragma mark - 加载科室列表
-(void)loadDepartmentInfo
{
    YJHDepartmentInfo *departmentModel = [YJHDepartmentInfo new];
    [departmentModel networkingSuccess:^(id result) {
        
        HTResults *mResult = result;
        YJHDeparmentResponseInfo *info = [YJHDeparmentResponseInfo new];
        info.list = mResult.data[@"list"];

        [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
            
            NSArray* mArray = [CDDepartmentInfo MR_findAllInContext:localContext];
            for (CDDepartmentInfo* item in mArray) {
                [item MR_deleteEntityInContext:localContext];
            }
            
            [CDDepartmentInfo mj_objectArrayWithKeyValuesArray:info.list context:localContext];

        } completion:^(BOOL contextDidSave, NSError * _Nullable error) {
        DDLog(@"存储完成");
        }];
        
    } failed:^(NSString *error) {
        DDLog(@"failed");
    }];
}

2.查找

CDDepartmentInfo *departmentInfo = [CDDepartmentInfo MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"departmentId like %@",_personInfo.departmentId]];

3.查找并排序

 NSArray *carrMonitor = [CDMonitorInfo MR_findAllSortedBy:@"kindId" ascending:YES];

4.更新数据

#pragma mark - 把新的体重身高插入输数据库
-(void)insertHeightAndWeightInSQL
{
    [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
        CDPersonInfo* userInfoCD = [CDPersonInfo MR_findFirstInContext:localContext];
        userInfoCD.height = [NSString stringWithFormat:@"%.2f",[self.personHeight floatValue]];
        userInfoCD.weight = [NSString stringWithFormat:@"%.2f",[self.personWeight floatValue]];
    } completion:^(BOOL contextDidSave, NSError * _Nullable error) {
        DDLog(@"更新成功");
}

5.清空数据

 NSArray *carrMonitor  = [CDNoReadMessageInfo MR_findAll];
    for (CDNoReadMessageInfo *noReadMessageInfo in carrMonitor) {
        [noReadMessageInfo MR_deleteEntity];
    }
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];

你可能感兴趣的:(Xcode8, MagicalRecord使用)