CoreData:如何为关联实体的NSSet添加条目及相关疑问
Hey there, let's work through your Core Data questions step by step!
Why Your Items Show Up in All Containers
The root issue is straightforward: when you create a new Items instance, you never set its container relationship property. This means every new item is unassigned to any container. If your TableView code isn't filtering items to only show those linked to the current container, all unassigned items will appear in every container's list.
Correct Way to Add Items to a Specific Container
There are two reliable ways to link an item to a target container—pick whichever fits your workflow:
1. Directly Set the Item's container Property
First, get a reference to your target container (e.g., from the selected TableView cell, or via a fetch request for a specific container). Then bind the new item to it during creation:
// Assume you have a reference to your target container: targetContainer: Container let itemEntity = NSEntityDescription.entity(forEntityName: "Items", in: managedContext)! let newItem = NSManagedObject(entity: itemEntity, insertInto: managedContext) as! Items newItem.setValue("item", forKeyPath: "text") newItem.setValue(count, forKeyPath: "index") // Critical: Link the item to the target container newItem.container = targetContainer do { try managedContext.save() } catch let error as NSError { print("Could not save item. \(error), \(error.userInfo)") }
2. Add the Item to the Container's items Set
Core Data automatically maintains bidirectional relationships, so you can also add the item directly to the container's item collection. Since items is an immutable NSSet, convert it to a mutable set first:
// Assume you have a reference to your target container: targetContainer: Container let itemEntity = NSEntityDescription.entity(forEntityName: "Items", in: managedContext)! let newItem = NSManagedObject(entity: itemEntity, insertInto: managedContext) as! Items newItem.setValue("item", forKeyPath: "text") newItem.setValue(count, forKeyPath: "index") // Add the item to the container's mutable item set let mutableItems = targetContainer.mutableSetValue(forKey: "items") mutableItems.add(newItem) do { try managedContext.save() } catch let error as NSError { print("Could not save item. \(error), \(error.userInfo)") }
Note: Both methods will automatically update the opposite side of the relationship. Setting
newItem.containeradds the item to the container'sitemsset, and vice versa—you don't need to do both manually.
Fixing Your Broken Container Update Code
Your earlier attempt to modify the container failed for two reasons:
- Incorrect entity name:
NSFetchRequest.init(entityName: "container")should be"Container"(Core Data entity names are case-sensitive). - Invalid property assignment: You tried to set a
textproperty onContainer, butContainerdoesn't have that property—it belongs toItems. This mismatch caused the crash.
Can Both Entities Have an index Property?
Absolutely! Different Core Data entities can share the same property name with no issues. Your index properties can serve separate purposes (e.g., sorting containers vs. sorting items within a container) and won't interfere with each other.
内容的提问来源于stack exchange,提问作者moyes

