iOS开发CoreData的多表关联

1、多表关联

  多表关联,对SQL 数据库的操作,在一张表的数据中可以引用另外一张表里的数据。通过 Entity 实体中的 Relationships 来实现,比起传统的 SQL 数据库来,更加简单。

2、如何关联

  本例中有三个实体Classes(班级)、Course(课表)、Student(学生),也就是三张表。

  Student学生只会在一个班级,多张课表两种关联属性;对应的Classes班级只会有多少个学生一种对应关系;Course课表也和多少个学生一种对应关系。

  以Student这个实体为例:studentCourses学生课表关联属性、studentClass学生班级关联属性。

  1)Relationship:关联属性名

  2) Destnation:关联属性的所属类

  3)Inverse:所属类的关联属性

  4)Delete Rule:删除规则

    No Action:表示删除学生时,班级和课表不做任何处理(认为学生还在,会造成异常,不建议使用)

    Nullify:表示删除学生时,班级和课表也会删除对应学生

    Cascade:表示删除学生时,班级和课表也会全部删除(级联操作,如果班级和课表也有级联操作,相关表都会删除)

    Deny:表示删除学生时,班级和课表会拒绝,只有班级和课表为nil时,才会删除学生

  5)Type:To One 和 To Many 两种选择,一个学生只会在一个班级所有选择To One,而课表一对多选择To Many

  另外两个实体的关联图:

  注意:在没有创建Course和Classes的关联属性时,Student的关联关系中Inverse没有选项的;

       如果在创建Course和Classes的关联属性之前创建了Student的关联属性,选择Course和Classes的Inverse之后,Student的Inverse会自动填充。

3、生成实体类

  以Student为例,选择To Many时生成的是NSSet集合!

#import "Student+CoreDataClass.h"


NS_ASSUME_NONNULL_BEGIN

@interface Student (CoreDataProperties)

+ (NSFetchRequest<Student *> *)fetchRequest;

@property (nullable, nonatomic, copy) NSString *age;
@property (nullable, nonatomic, copy) NSString *name;
@property (nullable, nonatomic, retain) Classes *studentClass;
@property (nullable, nonatomic, retain) NSSet<Course *> *studentCourses;

@end

@interface Student (CoreDataGeneratedAccessors)

- (void)addStudentCoursesObject:(Course *)value;
- (void)removeStudentCoursesObject:(Course *)value;
- (void)addStudentCourses:(NSSet<Course *> *)values;
- (void)removeStudentCourses:(NSSet<Course *> *)values;

@end

NS_ASSUME_NONNULL_END

4、简单使用

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"===%@",NSHomeDirectory());

    // Do any additional setup after loading the view, typically from a nib.
    self.delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    [self addData];
}
//添加一条数据
- (void)addData{
    Student *newEintity = [NSEntityDescription insertNewObjectForEntityForName:Model_Name inManagedObjectContext:self.delegate.persistentContainer.viewContext];
    newEintity.name = @"张三";
    newEintity.age = @"13";
    Classes *newClass = [[Classes alloc] initWithContext:self.delegate.persistentContainer.viewContext];
//    newClass.class_id = @"13";
//    newClass.class_name = @"高二";
    newEintity.studentClass = newClass;
    
    Course *newCourse = [[Course alloc] initWithContext:self.delegate.persistentContainer.viewContext];
//    newCourse.courseId = 1;
//    newCourse.courseName =@"语文";
//    newCourse.chapterCount = 23;
    [newEintity addStudentCourses:[NSSet setWithObject:newCourse]];
    [self.delegate.persistentContainer.viewContext save:nil];
}
原文地址:https://www.cnblogs.com/xianfeng-zhang/p/8301834.html