为什么我不能将 NSSet 保存为“对多”?核心数据中的关系?
在我的一个核心数据实体中,我与另一个实体具有一对多的关系。 假设我的家庭实体与人有一对多关系。
我可以毫无问题地创建家庭和个人。但是当我这样做时:
self.myFamily.people = [NSSet setWithArray:myPersonArray];
似乎没有分配给关系“人”的集合。 我目前正在将视图控制器中的一些代码重构为单例。这可能有什么关系吗?我可以保存所有其他对象,我可以创建和删除托管对象,我只是无法将一组对象分配给关系!
In one of my core data entities I have a one to many relationship with another entity.
Say my family Entity has a to-many relationship with person.
I can create families and persons no problem. but when I do a:
self.myFamily.people = [NSSet setWithArray:myPersonArray];
There doesn't seem to be a set assigned to the relationship 'people'.
I'm currently re-factoring some code away from the viewcontrollers into a singleton. Could this possible have anything to do with it? I can save all other object, I can create and delete managed objects I just can't assign a set of objects to a relationship!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能行不通的原因有几个。首先,如果您尝试在对象的初始值设定项中执行此操作,它将无法正确设置该值。当调用初始化器时,对象尚未添加到上下文中,因此设置值可能不会产生任何效果。其次,苹果建议不要直接设置一对多关系(抱歉,我找不到这个声明的文档,但它说的是如果你做得太多,它可能会停止工作)。相反,您应该使用动态创建的访问器或使用从
mutableSetValueForKey:
返回的值来修改它自动创建的可变集。或者
或者,因为你想更改整个集合,
你应该使用
mutableSetValueForKey:
而不是访问器返回的集合对象,因为访问器返回的对象不会调用 KVC 通知,而是来自mutableSetValueForKey:
会的。There are a couple of reasons why this might not work. First, if you are trying to do this in the object's initializer, it won't properly set the value. When the initializer is called, the object has not yet been added to the context, so setting a value may not have any effect. Secondly, Apple advises against setting a to-many relationship directly (sorry, I can't find the documentation for this statement, but it said something like if you do it too much it might stop working). Instead, you should modify the mutable set it creates automatically, either using the dynamically created accessors or by using the value returned from
mutableSetValueForKey:
.or
or, since you want to change the whole set
You should use
mutableSetValueForKey:
instead of the set object returned by the accessor because the object returned by the accessor won't call KVC notifications, but the object frommutableSetValueForKey:
will.当您报告此错误时,最可能的原因是尝试添加一组错误的对象类。您只能添加为数据模型中的关系定义的实体/类的对象。
因此,如果您有这样的数据模型:
...并且您有FamilyMO 和PersonMO 的NSManagedObject 子类,那么您只能分配一组PersonMO 对象到
Family.people
关系。如果您尝试分配这样的集合:...它将失败并且 IIRC,它会默默地执行此操作。
The most likely cause of this error as you report it is trying to add a set of the wrong class of objects. You can only add objects of the entity/class that is defined for the relationship in the data model.
So, if you have a data model like this:
... and you have NSManagedObject subclasses of
FamilyMO
andPersonMO
, then you can only assign a set ofPersonMO
objects to theFamily.people
relationship. If you tried to assign a set like this:... it would fail and IIRC, it would do so silently.