我有两个实体一个叫橱柜一个抽屉一对多关系橱柜>抽屉。对于橱柜,我使用了collectionView,并创建了tableView(抽屉)的segue。但我不知道我在抽屉里的时候怎么把新抽屉放进柜子里我这样保存我的橱柜:func saveCupboard(name: String, type: String){ let cupboard = NSEntityDescription.insertNewObject(forEntityName: "Cupboard", into: managedContext) as! Cupboard cupboard.name = name cupboard.type = type saveContext()}lazy var managedContext: NSManagedObjectContext = { var context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = self.storeCoordinator return context}()func saveContext() { if managedContext.hasChanges { do { try managedContext.save() } catch { print(error.localizedDescription) } }}我的话: override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDrawer" { let dst = segue.destination as! DrawerViewController guard let indexPath = collectionView.indexPathsForSelectedItems else{ return } dst.cupboard = ?? }}也许有人能帮我。提前谢谢你编辑: lazy var fetchedResultsCtrl: NSFetchedResultsController<Cupboard> = { let request: NSFetchRequest<Cupboard> = Cupboard.fetchRequest() let sort = NSSortDescriptor(key: "name", ascending: true) request.sortDescriptors = [sort] let fetchedCtrl = NSFetchedResultsController(fetchRequest: request, managedObjectContext: appDelegate.coreDataResource.managedContext, sectionNameKeyPath: nil, cacheName: nil) fetchedCtrl.delegate = self return fetchedCtrl}() 最佳答案 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDrawer" { let dst = segue.destination as! DrawerViewController guard let indexPath = collectionView.indexPathsForSelectedItems else{ return } dst.cupboard = cupboards[indexPath.row] as! Cupboard //Pass the cupboard to DrawerViewController. }}你可以把柜子递给上面的抽屉控制器。然后在DrawerViewController中添加新的抽屉时,您必须设置let newDrawer = Drawer(context:moc)newDrawer.cupboard = cupboard因为橱柜和抽屉之间有一对多的关系。关于ios - 在核心数据关系中添加子对象-Swift4,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47478693/ 10-11 20:26