If your Entity2's always relate to exactly one Entity1, I think the simplest way to achieve this involves defining a one-to-many relationship between Entity1 and Entity2 in your Core Data model.
- Select
Entity1. Under Relationships, click the + button to add a relationship. Name it something meaningful. Since you haven't told us the real names of your entities, I'll call the relationship entityTwos in this example.
- Set the Type of relationship to "To Many".
- If
Entity1 is not required to have any Entity2's, set the relationship to Optional.
- Set the Delete Rule to "Cascade" so that when
Entity1 is deleted, any related Entity2's are also deleted.
- Now, select
Entity2. Add a Relationship, give it a name (say entityOne) and set its Inverse to the name of the relationship created in Step 1 (entityTwos in this example).
- Uncheck the Optional option, and set the Type to "To One". Set the Delete Rule to "Nullify".
You'll also need to add properties for the relationships in your entity classes. In Entity1:
@NSManaged var entityTwos: NSSet
In Entity2:
@NSManaged var entityOne: Entity1
Having done that, you can easily access all the Entity2's related to an Entity1 without any querying, like this:
//here, entity1 is an instance of Entity1
entity1.entityTwos
What's really cool is you can also go the other way:
//here, entity2 is an instance of Entity2
entity2.entityOne