您的位置:首页 > 移动开发 > IOS开发

iOS —— MagicalRecord的使用

2015-08-31 16:53 465 查看
MagicalRecord是对CoreData的进一步封装,省去了许多冗余的代码,使用起来非常方便。

添加数据库

使用CoreData,在创建工程的时候,需要勾选CoreData,然后AppDelegate里就会多出来许多代码,异常繁琐,看一眼就不想再看第二眼了。

用MagicalRecord添加数据库就简单得多了,只需要在 - (BOOL)application:(UIApplication
*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法里写下面一句代码,就搞定了

[MagicalRecordsetupCoreDataStackWithAutoMigratingSqliteStoreNamed:@"MyDatabase.sqlite"];

创建model类

File -> New -> File -> iOS -> CoreData -> Data Model

或者直接 "command + N" 然后选择iOS -> CoreData -> Data Model

在新建的DataModel中添加实体和实体的属性, 如图:

添加好后,按下图所示生成model类,注意:选中Data Model,再通过Editor -> Creats NSManagedObject Subclass 生成对应的model类。

数据库的增删改查

增加

- (void)creatPersonWithName:(NSString *)name age:(NSString *)age gender:(NSString
*)gender phone:(NSString *)phone {
   Person *person = [PersonMR_createEntity];
    person.name = name;
    person.age = age;
    person.gender = gender;
    person.phone = phone;

    [[NSManagedObjectContextMR_defaultContext]
MR_saveToPersistentStoreAndWait];
}
首先调用MR_createEntity方法生成实体,然后给属性赋值,最后用[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait]保存到数据库。
查找

- (void)findPerson {
   NSArray *arr = [PersonMR_findAll];

    self.dataSource = [NSMutableArrayarrayWithArray:arr];
}
查找到所有的对象,存入到数组中。
还可以根据条件进行查找

[PersonMR_findFirst];
查找第一个

[PersonMR_findFirstByAttribute:@"gender"withValue:@"男"];
根据属性查找

还有一些其它的查找方式,可以根据需要选取

删除

Person *person =_dataSource[row];

[person MR_deleteEntity];

[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];

删除是针对实体对象进行删除,删除后仍然要保存到数据库
<
b9aa
p style="margin-top:0px;margin-bottom:0px;font-family:Menlo;color:rgb(88,126,168);">
修改

Person *person = _dataSource[row];

在这里对person对象的属性重新赋值

[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];

需要注意的是:在进行删除操作时,既要删除数据库,还要删除cell上展示的内容,这个删除的时机很重要。下面的代码仅供参考

//编辑删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle ==
UITableViewCellEditingStyleDelete) {
       
NSInteger row = indexPath.row;

        //第一步从数据库中删除
       
Person *person = _dataSource[row];
        [person
MR_deleteEntity];

        //第二步操作后的数据保存数据库

        [[NSManagedObjectContext
MR_defaultContext] MR_saveToPersistentStoreAndWait];

        //第三步从数组中清除掉

        [self.dataSource
removeObjectAtIndex:row];

        //第四步从tableViewCell中清除掉

        [tableView deleteRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationFade];
       
//第五步刷新
        [tableView
reloadData];

    } else
if (editingStyle ==
UITableViewCellEditingStyleInsert) {
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息