1.新建一个单视图时勾选Use Core Data
2.进入后会有一个 .xcdatamodeld 文件,鼠标单击
3.点击 Add Enity 创建新ENITIES (Enity: 实体)
4.建好Enity后,点击style,右下角
5.页面上有Enity的示意图形,选中后按Ctrl拖向另一个,即可将两者关联起来
6.每个示意图下部会出现一个RelationShips标签,点击标签为其取名
7.点击标签,在右边栏里再选中"盾牌"标志
8.在其下的Type中选择 to many 或者to one 以确定是一对多还是一对一
9.设立代理:AppDelegate*app = [UIApplication sharedApplication].delegate;
10.新建实体:Team *t1 = [NSEntityDescription insertNewObjectForEntityForName:@"Team" inManagedObjectContext:app.managedObjectContext]; t1.name = @"勇士";
Player *p1 = [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:app.managedObjectContext];
//p1.name = @"库里";
11.两个实体关联:
//子个体与集体个体关联: p1.myTeam = t1;
//集体个体与子个体关联:[t1 addPlayersObject:p1];
12.把关系保存: [app saveContext];
13.把保存的数据提取出来:先创建一个提取器,再用分解方法把提取到所有同名对象拆分成数组
//NSFetchRequest*request = [[NSFetchRequestalloc] initWithEntityName:@"Team"];
//NSArray*teams = [app.managedObjectContext executeFetchRequest:requesterror:nil];
//Team*t = teams[0];
网友评论