最近在使用MagicalRecord做数据持久层CoreData的操作库,今天做了一个多表关联数据的操作,整理了一个demo,特此记录一下。
关于如何使用Cocopads 和 MagicalRecord 库的引入就不做说明了。
1、首先创建一个数据Model,-file->new->CoreData ->选择data model,取名DemolModel

2、分别创建两个实体,UserEntity和MessageEntity

这里的两个表分别代表用户表和用户接受的消息列表,它们是一对多的关系,意思是一个用户会拥有很多条消息。下面设置他它们关系。
3、设置RelationHips
设置UserEntity对MessageEntity的关系是一对多,to many,如下图。新建时候,relationship可以随意取名,一般会取它要关联那个实体的名字(即Message),Destination:是选择需要关联的实体,Inverse:是选择在关联表里面建好的relationship。这是UserEntity的设置。

下面设置MessageEntity,它对于UserEntity是多对一的关系,设置如下

设置完实体之间的关系后,就可以生成它们对应的Model文件了。选择:Editor->Create NSManagedObject Subclass..,然后全选,下一步到完成即可。

自动生成的Model文件:

4、上面工作完成后,可以开始写程序了,
a、引入MagicalRecord库,配置基本设置
#import <MagicalRecord/MagicalRecord.h>
在AppDelegate的application didFinishLaunchingWithOptions设置CoreData本地数据库
[MagicalRecord setupCoreDataStackWithStoreNamed:@"MyDatabase.sqlite"];
在程序退出的时候设置:
- (void)applicationWillTerminate:(UIApplication *)application {
[MagicalRecord cleanUp];
}
b、添加数据到数据库

c、查询数据

d、输出结果
MagicalRecordDemo[1116:31713] 用户数: 1
MagicalRecordDemo[1116:31713] demowork
MagicalRecordDemo[1116:31713] Hello
MagicalRecordDemo[1116:31713] Bye Bye
网友评论