美文网首页
CoreData第二课

CoreData第二课

作者: 贼海鸥 | 来源:发表于2021-05-26 18:04 被阅读0次

两个实体之间的关联,比如,一个人有很多书,就是一对多的关系,一个人只能有一个脑袋,就是一对一的关系。如何处理这种关系,看下面。
第一步,先创建实体Book,如下图


Book实体

同时,在Person实体中添加books属性


Person实体
然后就是Person和Book的一对多的关系
关系图
在代码里面,为Person模型添加Book数据
- (IBAction)addAction:(id)sender {
    NSEntityDescription *des = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context];
    Person *p = [[Person alloc] initWithEntity:des insertIntoManagedObjectContext:self.context];
    p.name = @"lhx";
    p.age = arc4random() % 100 + 10;
    
    NSEntityDescription *bEntity = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:self.context];
    Book *book = [[Book alloc] initWithEntity:bEntity insertIntoManagedObjectContext:self.context];
    book.name = @"西游记";
    book.price = 36.5;
    [p addBooksObject:book];
    
    [self.dataArray addObject:p];
    [self.myApp saveContext];
    [self.tableView reloadData];
}

然后,在需要的地方取

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    Person *p = self.dataArray[indexPath.row];
    // 一对多,books就是一个数组。一对一,books就是book的模型数据
    Book *b = p.books.firstObject;
    if (b) {
        cell.textLabel.text = [NSString stringWithFormat:@"%@-%lld,拥有的书-%@,价格是%.2f", p.name, p.age, b.name, b.price];
    } else {
        cell.textLabel.text = [NSString stringWithFormat:@"%@-%lld", p.name, p.age];
    }
    
    return cell;
}

相关文章

网友评论

      本文标题:CoreData第二课

      本文链接:https://www.haomeiwen.com/subject/iktlsltx.html