views:

296

answers:

1

Let's say I have 4 entities in my data model: Person, Car, Pet, and Photo. I would like a relationship from Person Car and Pet to the Photo entity, in that I'd like each of those things to contain a photo of that item. So far, no problems. Though where it gets tricky is the inverse relationship, which is where the photo entity would want to point back to the attached item. I would prefer to either have no inverse relationship at all, so the only attribute in Photo would be a UIImage, or maybe a single attachedItem inverse relationship. If I do that, I could only select one of those items to attach to my relationship.

Would it be better to leave this as a unidirectional relationship? Maybe I could make an abstract entity called "AttachableItem" and make Person Car and Pet be children of this, then make my inverse relationship point to AttachableItem. I'm not sure which way would be best.

+3  A: 

I would make Photo an abstract entity and create PersonPhoto, CarPhoto, and PetPhoto entities each with Photo as its parent entity.

Person, Car, and Pet would have a to-one relationship with PersonPhoto, CarPhoto, and PetPhoto, respectively. Then, PersonPhoto, CarPhoto, and PetPhoto could each have a single required to-one inverse relationship with Person, Car, and Pet, respectively.

The Photo entity would still have the single attribute. You can store the images in files in your app's Documents directory and save the filename as this attribute. This approach is recommended in this answer. Alternately, you can store images directly in Core Data as a transformable attribute by converting them to NSData using UIImagePNGRepresentation() or UIImageJPEGRepresentation().

gerry3