title: Core Data Coding Pattern
body: <p>I have been working with C# using a repository design pattern with Entity Framework (EF) that allows me to interact with the database using a generic class for each table. </p>
  
  <p><a href="https://i.stack.imgur.com/HgLHP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HgLHP.png" alt="enter image description here"></a></p>
  
  <p>This repository has all the functions that I would need such as: Adding a new entity into the database, updating an existing entity, deleting an entity, saving the context and so on...</p>
  
  <p>Take, for example, I have an entity called 'Person' in the database. I would create a new class called PersonRepository which had all the functions I would need to change/add a value to the database.</p>
  
  <p>As a result, to interact with the database, you create an instance of the repository class. This then allows you to call the functions of this class which in turn interacts with the database. The idea of this pattern is that all your database calls for an entity are isolated into a single class, this improves testability and separation of concerns.</p>
  
  <p>I am learning how to use Core Data in my Swift programs and it appears to be similar to that of EF in C#. I have created the entities in the .xcdatamodel file and created the associated Cocoa Touch class via the Editor > Create NSManageedObject subclasses option. </p>
  
  <p>I used the 'Category/Extension' CodeGen option, so, I then created a new class called 'Exercise'. From what I have read, this class can contain additional logic such as overriding the prepareForDeletion method. Does this mean I can add the addEntity, updateEntity functions onto this method and then call them from other code files?</p>
  
  <p>My questions are:</p>
  
  <ol>
  <li><p>Can I implement the same repository pattern that I can use in C#? 
  I believe this would be on the generated class of my entity (see image below) </p></li>
  <li><p>Where do I place all my database call functions? If I can use this repository pattern I will place them on there, however, if I cannot, do I place them in a separate code file? Should I place them on the generated entity file which is created for the purposes of adding additional logic?</p></li>
  </ol>
  
  <p><a href="https://i.stack.imgur.com/ImPWA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ImPWA.jpg" alt="enter image description here"></a></p>
  
  <ol start="3">
  <li>If I can use the repository pattern, is there a way to get the context injected into this class, or, do I have to call a getContext method each time I want to change it? In C# we can use the services to inject the context into the class each time I want to make changes to the database - I am unsure if the same is possible in Swift.</li>
  </ol>