Magical Record是什么
安装
-
新建一个项目,注意在向导中不要勾选Core Data。
-
下载Magical Record,并把MagicalRecord目录拖拽到工程中,记得勾选copy items into group folder。
-
为项目添加CoreData FrameWork。(点击工程根节点,然后依次Targets > Build Phases > Link Binary With Libraries > + > CoreData.framework > Add)。
-
添加Magical Record的头文件到*-Prefix.pch:
-
1
#import "CoreData+MagicalRecord.h"
-
使用Magical Record
初始化Magical Record
1
2
3
4
5
6
7
8
9
10
11
12
|
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[MagicalRecord setupCoreDataStackWithStoreNamed:@
"MyDatabase.sqlite"
];
// ...
return
YES;
}
- (void)applicationWillTerminate:(NSNotification *)aNotification
{
[MagicalRecord cleanUp];
}
是否比Core Data默认的初始化简洁多了呢?
|
查询记录
-
12345678
//查找数据库中的所有Person。
NSArray *persons = [Person MR_findAll];
//查找所有的Person并按照first name排序。
NSArray *personsSorted = [Person MR_findAllSortedBy:@
"firstname"
ascending:YES];
//查找所有age属性为25的Person记录。
NSArray *personsAgeEuqals25 = [Person MR_findByAttribute:@
"age"
withValue:[NSNumber numberWithInt:25]];
//查找数据库中的第一条记录
Person *person = [Person MR_findFirst];
添加记录
1
2
3
4
5
6
7
8
|
Person *personAdd = [Person MR_createEntity];
personAdd.firstName = @
"mengmeng"
;
personAdd.sex = @
"nv"
;
personAdd.age = [NSNumber numberWithInt:14];
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
[[NSManagedObjectContext MR_defaultContext] MR_saveOnlySelfWithCompletion:^(BOOL contextDidSave, NSError *error) {
NSLog(@
"保存完成了"
);
}];
|
更新记录
-
123
Person *person = ...;
//此处略
person.lastname = object;
[[NSManagedObjectContext MR_defaultContext] MR_save];
删除记录
-
123
Person *person = ...;
//此处略
[person MR_deleteEntity];
[[NSManagedObjectContext MR_defaultContext] MR_save];