user2632918
user2632918

Reputation:

Many-to-Many Relation with CoreData

Relation

Hallo,

I have the datamodel in the picture. But I need the following model.

When I add a damage report Damage, this report should relate to one or many Address objects from the stored addresses in the datastore.

Every Address should also added only once to the datastore.

How should I define the relationship between Address and Damage?

Damage: Damage

Address: Address

Upvotes: 0

Views: 37

Answers (1)

Hal Mueller
Hal Mueller

Reputation: 7665

You can make the relationship between Damage and Address many to many. Select the damage relationship of Address in the model editor, and switch the type from To One to To Many.

The word "damage" is not a countable noun. A better choice for that entity name would be DamageReport or DamageIncident.

As for having a unique Address entity for each address, you'll have to enforce that yourself, with code. Core Data cannot do this for you. Choose which attributes of the Address entity make it unique: probably street and zipcode. Then write a method that accepts street, zipcode, and managed object context, and searches Core Data for an Address object matching those parameters. That method will return the existing object, if any, or will create a new one, populated with street and zipcode, and return it to you for the rest of the initialization. This pattern is commonly called "find or create", and is documented in Apple's Core Data programming guide.

Upvotes: 0

Related Questions