0

我正在做一个涉及充分利用核心数据的项目。几个月以来我一直在使用它。我有一个小问题。我有两个不同的实体,一个名为 Student 的实体和另一个名为 Courses 的实体。学生和课程之间的关系是一对多的。我经常从远程 json 更新实体。因此,有时 Courses 实体中存在与 Student 实体没有关系的悬空指针。需要删除此类实体。删除此类对象如何更好?

              Courses(points to student) <------------- Student ----------------> Course (Points to student) 
                                                           |
                                                           |
                                                           |
                                                           |
                                                Course (Points to student)

                       Course(has no pointer to student, no foreign key to relate with student)
4

2 回答 2

1

您确定要在没有学生的情况下删除课程吗?当然可能是有效的。我认为你应该取消关系,所以当你删除一个学生时,所有指向它的课程都会停止引用那个学生。

您可能需要检查您的关系删除规则,以便在我看来它们应该被取消。

于 2012-07-05T11:55:17.267 回答
0

执行此操作的简单方法是创建一个获取请求并针对Courses. 显然,您需要使用 aNSPredicate来删除Courses没有学生的。

如果你Courses有一个反向 rel to Student, called coursesToStudent,你可以设置以下谓词。

[NSPredicate predicateWithFormat:@"coursesToStudent == nil"];

在这里,我认为它CoursesStudent.

这样,获取请求的结果将Courses没有学生。有了结果,打电话deleteObject就完成了。

有关使用谓词设置获取请求的信息,请参阅Filter NSFetchedResultsController for nil value? .

关于你的模型,我会设置另一个。例如使用三个实体:

Student
Course
Enroll

在哪里

Student
- attributes you want
- toEnroll [one-to-many rel to Enroll with cascade rule]

Course
- attributes you want
- toEnroll [one-to-many rel to Enroll with cascade rule]

Enroll
- attributes you want
- toStudent [one-to-one rel to Student with nullify rule]
- toCourse [one-to-one rel to Course with nullify rule]

希望有帮助。

于 2012-07-05T12:45:02.717 回答