我有一个包含以下实体的应用程序:Station,Program和StationProgram:
Station <-->> StationProgram <<--> Program
电台是指电动电梯,程序是浇水程序(数据库中可以有N个程序),而StationProgram有一个属性,用于指示电台在程序中浇水的时间。
关键是我可以在DB中(在它们各自的View Controllers中)正确创建Station和Program的实例。但是,我有一个TableViewController,对于在前一个控制器中选择的给定站,我想显示所有可用的程序,UISwitch指示该程序是否已与该站关联。最初,站和程序之间没有关联。用户可以与数据库中的所有现有程序进行交互,并为此工作站激活它们(将表格行中显示的指向程序的UISwitch设置为打开)。最后,当用户想要保存配置时,我想在表StationProgram中插入数据。到目前为止,为了简化,我只想手动为时间分配一个时间,例如2分钟。我有以下代码,但是当我尝试映射时执行崩溃:
@IBAction func saveTapped(sender: AnyObject) {
// Reference to our app delegate
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
// Reference moc
let context: NSManagedObjectContext = appDel.managedObjectContext!
let en = NSEntityDescription.entityForName("Station", inManagedObjectContext: context)
station.setValue(textFieldStationName.text as String, forKey: "name")
let en2 = NSEntityDescription.entityForName("StationProgram", inManagedObjectContext: context)
// The variable activePrograms contains the row of the table where this program is shown, and the wateringTime
for (selectedCellId,time) in activePrograms {
var newStationProgramInstance = StationProgram(entity: en2, insertIntoManagedObjectContext: context)
let program: NSManagedObject = programList[selectedCellId] as NSManagedObject
// Map our properties
newStationProgramInstance.wateringTime = time
// station is a variable of type Station that is filled from the previous controller
newStationProgramInstance.toStation = station as Station
newStationProgramInstance.toProgram = program as Program
}
context.save(nil)
self.navigationController.popViewControllerAnimated(true)
}
具体而言,执行在“&station;&new; NewStationProgramInstance.toStation = station”作为Station&#34;行崩溃。它在
处说swift_dynamicCastClassUnconditional线程1:EXC_BREADKPOINT(代码= EXC_I386_BPT,子代码= 0x0)
非常感谢你的帮助。
答案 0 :(得分:0)
在核心数据中,您可以使用多对多关系来建模这种关系,而不是单独的连接表。
Station (programs) <<----->> (stations) Program
使用连接表的唯一合理理由是,如果要添加并保留有关关系本身的其他信息(例如 dateCreated 或类似信息)。我怀疑你的情况是这样的。
现在这种关系的创造变得微不足道了。如果使用反向关系正确设置模型,就可以单向执行。
newStation.addProgramsObject(newProgram)