开发者

What's the Best Way to Simulate an Array Type Attribue in Core Data?

开发者 https://www.devze.com 2023-01-11 00:28 出处:网络
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 shoul

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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消