Suppose there is a web service returning a JSON response like this:
{
"id": "123",
"name": "John Doe",
"phone": {
"country_code": "1",
"area_code": "11",
"number": "55544433"
}
}
This is describing a Person entity, but inside this entity, there is the phone property containing an embedded object.
Phone is not an entity and it is not referenced by an id, it is fully contained inside the scope of this Person entity. However, it would be desirable to map it to a Phone @interface in my code (for example, it could have a method "formatAsString" that returns a formatted string like this: "+1 (11) 55544433")
How should I handle this case when mapping the model to iOS Core Data?
Create a Person
entity with a to-many
(or to-one if there is only one phone #) relationship to a Phone
entity.
The Phone
entity will have a to-one relationship to a Person
entity.
In addition it will have the inner structure you described (country_code,area_code,number).
You don't need an id
property in order to create a CoreData entity.
You could set the relationship to 'cascade', so that when a person is deleted all related phone numbers are deleted.
When you traverse you JSON response, read the "phone" key into a Phone
entity and the its person
property to the person you are currently traversing.