我正在使用核心日期来保存以下实体。
培训计划>活动>系列
在程序中保存活动时,我正在使用该方法。
let programTranningDB = NSEntityDescription.insertNewObject(forEntityName: "ProgramTranningDB", into: self.getContext())
(programTranningDB as! ProgramTranningDB).addToActivities(activities)
do{
try self.getContext().save()
} catch {
print(error)
}
如何将系列添加到活动中? 有人可以帮我吗?
答案 0 :(得分:0)
假设您的模型看起来像这样:
您将系列的实例添加到活动,就像将活动添加到培训计划< / strong>。
您可以在addToSeries(_:)
我通常将所有数据域逻辑包含在一个类中,以帮助测试和分离关注点。
class DomainLogic {
var context: NSManagedObjectContext
init(context: NSManagedObjectContext) {
self.context = context
}
func addNewProgram(named: String) -> TrainingProgram {
guard let program = NSEntityDescription.insertNewObject(forEntityName: "TrainingProgram", into: context) as? TrainingProgram else {
preconditionFailure("TrainingProgram should be created here")
}
program.name = named
return program
}
func addNewActivityToProgram(_ program: TrainingProgram) -> Activity {
guard let activity = NSEntityDescription.insertNewObject(forEntityName: "Activity", into: context) as? Activity else {
preconditionFailure("Activity should be created here")
}
program.addToActivities(activity)
return activity
}
func addNewSeriesToActivity(activity: Activity) -> Series {
guard let series = NSEntityDescription.insertNewObject(forEntityName: "Series", into: context) as? Series else {
preconditionFailure("Series should be created here")
}
activity.addToSeries(series)
return series
}
}
这将导致一个简单的序列,以创建一个新的系列并将其添加到链中。
var context: NSManagedObjectContext!
func createSeries() -> Series {
let logic = DomainLogic(context: context)
let program = logic.addNewProgram(named: "Fatima's Program")
let activity = logic.addNewActivityToProgram(program)
let series = logic.addNewSeriesToActivity(activity: activity)
return series
}
您还需要逻辑来从数据库中恢复现有的 TrainingProgram 对象。