Henny Lee
Henny Lee

Reputation: 3052

CoreData relationships loops?

I have 2 entities Buildings and GroupOfBuildings:

Building1 has: GroupOfBuildings1
Building2 has: GroupOfBuildings1

GroupOfBuildings1 has: Building1, Building2 and Building3

Relationships:

Building <<----> GroupOfBuildings
Building <<--->> GroupOfBuildings
Building <---->> GroupOfBuildings

relationships


Question:

GroupOfBuildings has a group of Buildings which can be used in Buildings and also contains a mainBuildings reference to Buildings. On top of it, Buildings needs a reference to GroupOfBuildings. Is this the right way of setting up the relationships or is there another way of doing this? It seems setting multiple (looping) relationships isn't how I should do things. Any advice?


Sample code:

let buildingDescription = NSEntityDescription.entity(forEntityName: "Buildings", in: context)!
let building1 = Buildings(entity: buildingDescription, insertInto: context)
let building2 = Buildings(entity: buildingDescription, insertInto: context)
let building3 = Buildings(entity: buildingDescription, insertInto: context)

let groupOfBuildingDescription = NSEntityDescription.entity(forEntityName: "GroupOfBuildings", in: context)!
let groupOfBuildings1 = GroupOfBuildings(entity: groupOfBuildingDescription, insertInto: context)

groupOfBuildings1.mainBuilding = building1
groupOfBuildings1.groupOfBuildings = Set([building2, building3])

building1.groupOfBuildings = groupOfBuildings1
building2.groupOfBuildings = groupOfBuildings1

Note:

I have another question which uses the same data, but questions are different.

Upvotes: 0

Views: 88

Answers (1)

trapper
trapper

Reputation: 11993

This is hard to follow due to the bad naming. Call things what they are and don't pluralise the object names. Buildings should be called Building, GroupOfBuildings probably BuildingGroup, no idea what 'items' refers to...

That said there is no problem with setting up multiple relationships between the same objects. You can have buildingGroup.mainBuilding, buildingGroup.otherBuildings, buildingGroup.extraBuildings all fine, just name them properly so they make sense.

Upvotes: 1

Related Questions