MagicalRecord relationship mapping duplicates objects despite primary keys

不问归期 提交于 2019-12-04 12:31:51

问题


I'm in need of some assistance for an issue I am experiencing with MagicalRecord data importing. I was under the impression that MagicalRecord was able to handle relationship mapping without duplicating objects by looking at the primary keys (relatedByAttribute).

Here's a simple JSON:

[
  { 
    parentId: "<unique id>",
    parentName : "<name>",
    children : [
                  {
                     childId: "<unique id>",
                     childName: "<name>"
                  },
                  {
                     childId: "<unique id>",
                     childName: "<name>"
                  }
               ]
  },
  { <another parent with children> }
]

I've got an NSManagedObject Parent which has a to-many relationship with a Child NSManagedObject. The relationship name is children and I've set the relatedByAttribute on the Child and Parent to childId and parentId respectively.

When I parse the JSON the Parent is not duplicated and it correctly checks for the primary key and uses the existing object if present. However for the Children it duplicates the objects every time I parse the JSON. If I parse the Children individually (so JSON just contains an array with children dictionaries) it has no problem correctly mapping the data and using existing objects for Children that already exist in the database.

Did I misunderstand and have the wrong expectations for how MagicalRecord maps relationships? Currently I've setup an extension class with 'importChildren:` where I can handle all the look-ups manually and create/import the objects accordingly.

Thanks!


回答1:


I managed to solve this a while back.

What I did was add relatedByAttribute in the User Info dictionary for the children relationship AND for the Child entity as well.

So click on the relationship and set relatedByAttribute to childId (in my example above) and also click on the Child entity on the left and for this also set relatedByAttribute to childId in the User Info dictionary for the entity itself.

This allows Magical Record to correctly map using existing objects or create new ones if needed - granted that the ID attribute is 100% unique!



来源:https://stackoverflow.com/questions/14595815/magicalrecord-relationship-mapping-duplicates-objects-despite-primary-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!