0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Sounds correct. Is the id completely optional, even when saving the entity to a persistent store? (say, for instance, that I'm saving the Person together with its Phone). Thanks!
CoreData does not provide an automatic way of uniquing a given property. the only thing guarantied to be unique is the objectID property of the managed object. the objectID property is managed by CoreData, and you cannot change it yourself. When you save, the entities will be given a permanent objectID, regardless of the properties you set on those objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.