views:

32

answers:

3

I've got a list of contacts, each having several emails.

Should I create a Contact Core Data entity and a Email entity and link several email objects to one contact object? Or should I do it another way e.g concatenate all the emails and store them as one big string?

What's the cleanest and most efficient way to deal with such a configuration ?

Thanks

A: 

Should I create a contact CoreData entity and a email entity and link several email objects to one contact object ?

This solution sounds reasonable. Still it is not an "array type attribute" as to-many relations are unordered sets instead of ordered arrays.

Martin Brugger
+1  A: 

Always think of Core Data as an object graph and model your data accordingly.

You should have a Contact entity and an Email entity. The email should be on the other end of a one-to-many bi-directional relationship with Contact. If you care about a specific order then you should also have some orderable value in the Email entity for later sorting.

Marcus S. Zarra
Ok thanks. It just seemed to me this solution would be less efficient for fetching data but maybe it insignificant.
CodeFlakes
It is not less efficient. Core Data is far more efficient with object reuse, etc. than your own code would be. With the addition of filtering and searching, it is far more efficient.
Marcus S. Zarra
A: 

Your entity graph would look something like (pseudocode):

Contact{
    name:string
    emailAddress:string
    //...other attributes of contacts
    emails<--(optional,cascade)-->>Email.contact
}

Email{
    from:string
    // ... other attributes of emails
    contact<<--(required,nullify)-->Contact.emails
}

In both the entity (abstract) and object (concrete) graphs, you need only link contacts to their emails without any particular order. You shouldn't worry about ordering the relationships in the entity graph because the order in which you want to display the objects might change from moment-to-moment. That order is determined by the sort descriptor of each particular fetch request. The fetch request will return an array in any order you define. E.g one time you want emails sorted by date received, another time by from, another time by some other attribute. You can even resort the array the returned by a fetch to get exactly the order you want.

You just want to make sure that the entities have attributes that capture the information on which you want to sort.

In the very rare cases in which some type of ordering is absolutely required in the entity graph itself, you should add a ordering attribute to the entity itself and write custom code to maintain the sort order.

TechZen