<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Filipe Martins on Medium]]></title>
        <description><![CDATA[Stories by Filipe Martins on Medium]]></description>
        <link>https://medium.com/@fms_martins?source=rss-3f6d9add4d65------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YKE5Rq0F3v3wz9-P.png</url>
            <title>Stories by Filipe Martins on Medium</title>
            <link>https://medium.com/@fms_martins?source=rss-3f6d9add4d65------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:28:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fms_martins/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Core Data on iOS 10, a brief overview with an Example]]></title>
            <link>https://medium.com/runtime-revolution/core-data-on-ios-10-a-brief-overview-with-an-example-dc6e0ce844a5?source=rss-3f6d9add4d65------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc6e0ce844a5</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Filipe Martins]]></dc:creator>
            <pubDate>Thu, 23 Mar 2017 14:04:49 GMT</pubDate>
            <atom:updated>2017-04-27T10:51:22.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NRxJZCSvrPRr2WQJfDJiQ.jpeg" /></figure><p>Core Data is a framework, provided by Apple, to be used on Applications for iOS and macOS. As Apple states, it is not a database, but instead a persistence framework that commonly uses SQLite to store and retrieve structured data. For programmers, it operates purely on the object level without having to worry about the details of storage and retrieval.</p><p>At first the Core Data framework may seem difficult to understand. But the API is intuitive and concise, and once you understand the <strong>Core Data stack</strong>, it starts to make sense, and you can quickly adapt to it. The most common mistake, is to start using the Core Data without understanding how its pieces fit together and relate to each other.</p><p><strong>The Core Data Stack</strong></p><p>The Core Data stack handles all of the interactions with the external data store and consists of three primary tools: the <strong>Managed Object Model</strong>, the <strong>Persistent Store Coordinator</strong> and the <strong>Managed Object Context</strong>. It may sounds like a lot of pieces to be used, but since you setup all this parts, you will not need to make much changes, and you will be using mostly only the Managed Object Context.</p><p>The <strong>Managed Object Model</strong>, describes the schema that you will be using in your application. It loads the file into memory, often referred to as <em>“mom”</em>, generated from the <em>.xcdatamodeld</em> of your Xcode project. If the application is unable to find or load the file fails to load it and raises a <em>“Fatal Error”</em>. In Xcode, by selecting this <em>.xcdatamodeld</em> file, you will be able to use the visual editor to define the entities with their attributes and relationships.</p><p>The <strong>Persistence Coordinator</strong> verifies that the data is in a consistent state that matches the definition on the model layer, and is responsible for extracting instances of entities from that data. A common <em>“Fatal Error”</em> a programmer can face is when he makes changes on the Managed Object Model. For example add a new attribute to a entity, and re-run the application with previous stored data. In this situation, you have two options. You can prepare a migration, if you already have your application on the App Store. Or you can just reinstall the application, since it doesn’t make sense to have a migration developed if no one is using your application, and this will not be necessary for anyone other than you.</p><p>And finally the <strong>Managed Object Context</strong>, which is the one that your source code will be interacting with the most, is responsible for managing objects created and returned using Core Data. It operates <em>in-memory</em>, not only for speed, but also to keep your model objects’ attributes updated across your application. For object graph changes that affect multiple objects, it is much faster if they are already in memory, rather than searching for them again in the database. You can modify those objects however you like, and unless you actually save those changes, the persistent store remains unaltered. And by tracking changes, the context is able to provide undo and redo support for you.</p><p><strong>Creating a Model layer on the Managed Object Model</strong></p><p>First, let’s start a new project on Xcode <strong>(File &gt; New &gt; Project…)</strong>. From the wizard select the <em>“Single View Application“</em>, and on the next step, enable the option <em>“Use Core Data”</em> and press <em>“Next”</em>, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7NBI84RTCBDp2rQ0MDMtg.png" /></figure><p>After you create your project, you will find the <em>.xcdatamodeld</em> file, as described before. Go ahead and select that file to open the <em>Xcode Data Model editor</em> as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zfDPusB36dmEP_ogTfX0Fw.png" /></figure><p>From the bottom option <em>“Add Entity”</em> you can add as many entities\tables your model needs to have. Go ahead and click that option to create a new entity.</p><p>By default, Xcode creates an entity with the name “Entity” and without any attributes. You can change the name like you would change a file name on Finder, but you can also use the inspector to perform this change. The inspector is the right bar, if you don’t have it visible go to <strong>View &gt; Utilities &gt; Show Data Model Inspector</strong> to enable it.</p><p>On the image below we will use the inspector to change the name of the entity to <em>“Task”</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnf84eWmbLXbww0bLArTSA.png" /></figure><p>After you press enter, the <strong>Class</strong> name, below the section <strong>Entity</strong>, will also be updated with the desired name. Note that the entity name and the class name don’t need to have the same value, but from my experience it is preferable you do so to avoid misunderstandings in the future. After this, go ahead and click the plus (+) sign on the section <em>Attributes</em> to add a new attribute to this entity. In this case, the editor will be expecting you to change the name and select a valid type. If you don’t select a valid type it will keep showing an error. I will change the attribute name to <em>“name”</em> and set the type to <em>“String”</em>. Another note here, there are names with internal conflicts that can’t be used. For example, the name <em>“description”</em> clashes with an internal implementation of the Core Data objects, and cannot be used. After you create this new attribute it should look like the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TkuYO1TuHBr8yJYH3u1DLQ.png" /></figure><p>Note that we don’t need to create an attribute for a primary key. That is one of the responsabilities of Core Data and it is the framework that will create the logic for your entity internally.</p><p>For a better representation and understanding of the Managed Object Model, go ahead and add one more attribute to this entity, named <em>“completed”</em> with type <em>“Boolean”</em>.</p><p>Also go ahead and create a new entity named <em>“Note”</em> with one attribute named <em>“text”</em> and type <em>“String”</em>.</p><p>After this we want to create a <strong>relationship</strong> between these two entities, where a task can have multiple notes. To setup this relation, select the entity <em>“Task”,</em> and from the section <em>“Relationships”</em> click on the plus (+) sign to create a new attribute. Then rename that relationship attribute to <em>“notes”.</em> From the <em>“Destination”</em> section select the desired entity <em>“Note”.</em> Now in the <em>Data Model Inspector (Right Bar) </em>change the <strong>Relationship Type</strong> to <em>“To Many” </em>as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xa8uVAHj0grwFELgzHzxuw.png" /></figure><p>You will notice that a warning appears. This warning alerts you to define an <strong>inverse</strong> relationship to the entity <em>“Note”</em>. This is not strictly required, but setting the inverse relationship will help Core Data ensure the consistency of the object graph when a change is made.</p><p>Go ahead and select the entity <em>“Note”</em> and add a new relationship attribute, then rename it to <em>“task”.</em> From the <em>Destination</em> select the entity <em>“Task”</em>. To remove the warning from the column <em>Inverse</em>, select the attribute <em>“notes”.</em> This will also update the relationship attribute on the entity <em>“Task”</em> to <em>“task”.</em> By default the relationship is set as <em>“To One”</em> so you don’t need to change anything on this side. When you’re done it should look like the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ghklszx-aqLym89i2Sr4g.png" /></figure><p>With this, we have setup a basic <strong>Managed Object Model</strong> with a relationship <em>One-To-Many.</em> Where a <em>“Task”</em> can have multiple <em>“Note” </em>entities, and a <em>“Note”</em> can have one <em>“Task”</em>. You will only need to perform changes if you want to increase the complexity of your stored data, such as adding a new entity or attribute; otherwise, you won’t need to worry about this section any time soon.</p><p><strong>Initializing the Persistence Coordinator</strong></p><p>In iOS 10, you only need to specify the container name with the same name as your . xcdatamodeld file, which will return the “mom” file from the compiler to the coordinator.<br>Selecting the AppDelegate.swift file you will find the common used code, inside the class, that initializes the coordinator, like the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bda18f49d24caf67f41a5c2e9cfedc9a/href">https://medium.com/media/bda18f49d24caf67f41a5c2e9cfedc9a/href</a></iframe><p><strong>Designing a simple User Interface</strong></p><p>Since the main goal of this article is not related to how we design user interfaces, I will give you a quick setup to support this article. To start, go ahead and select the <em>Main.storyboard</em>. On the Visual Editor drag a <em>“Toolbar”</em> from the inspector and drop it into the controller view. Also drop a <em>“Table View”</em> into the controller view, and resize it to have the same look as shown below. One thing to note here, if you don’t setup the auto layout constraints, you may have some issues regarding the interface layout if you use a device with diferent aspect ratio (On the final code I have included the auto layout constraints).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJlu6i1T0fQgffe1woY3Og.png" /></figure><p>Double tap on the element <em>“Item”</em>, from the bottom <em>Toolbar</em>, and rename it to <em>“Add”</em>. Also drag and drop a <em>“Table View Cell”</em> from the inspector to the <em>Table View</em>. Select the dropped cell, and from the inspector set an <em>Identifier</em> string to this prototype cell, in this case I will use the string <em>“Cell”</em>. It should look like the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNrlSDybZnwMJcprkWKjLw.png" /></figure><p>Next, we need to indicate to the Table View which object will be responsible to return objects for it. To do this, right click on the <em>“Table View”</em> object from the “<em>View Controller Scene”</em> hierarchy, and link the <strong><em>dataSource</em></strong> and the <strong><em>delegate</em></strong> to the <em>View Controller</em>, like in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKxfErNrKJt57agx9uZoLA.png" /></figure><p>Going back to code, add the following instance and method into the <em>ViewController.swift</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/596c7307a534c6515f8d3240c232106c/href">https://medium.com/media/596c7307a534c6515f8d3240c232106c/href</a></iframe><p>Returning to the <em>Visual Editor</em>, right click on the <em>View Controller</em> object from the <em>View Controller Scene</em> and connect the instance <em>“tableView”</em> to the <em>Table View</em> and the method <em>“addTask:”</em> to the button “Add” on the bottom toolbar. It should look like the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0PBtfUf9b95MaLIXAhPUfg.png" /></figure><p>And with this we have a basic user interface to support this use case for Code Data. I will not extend all user interfaces to fulfill the entire model layer, but you have the idea how to propagate to additional view controllers. Now let’s move to the Managed Object Context to create, update and delete objects!</p><p><strong>Using the the Managed Object Context</strong></p><p>First let’s import the Core Data framework references to the <em>ViewController.swift</em> as shown below to have access to the functionalities of the Core Data on this class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86cf5ff85bdae76587c0979724ce2a42/href">https://medium.com/media/86cf5ff85bdae76587c0979724ce2a42/href</a></iframe><p>Then add to your <em>ViewController.swift</em> a variable that will have the reference to the managed object context. The ViewController.swift should have something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab99e3eb479c03147bae59a7002a2ffa/href">https://medium.com/media/ab99e3eb479c03147bae59a7002a2ffa/href</a></iframe><p>Now let’s move back to the <em>AppDelegate.swift</em> and in the method <strong><em>application:didFinishLaunchingWithOptions:</em></strong> include the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5baa18e797836051abc89b86f7677b38/href">https://medium.com/media/5baa18e797836051abc89b86f7677b38/href</a></iframe><p>To fetch objects from the database the best aproach, and the solution Apple wants us to use, is the <em>NSFetchedResultsController</em>. Fetched results controllers can fetch efficiently records from a predicate and a sort order. It can also monitor changes to objects in the associated managed object context, and report changes in the result sets to its delegate.</p><p>To implement the fetched results controller, let’s create an instance of <em>NSFetchedResultsController</em>, on the <em>ViewController.swift</em> file. After creating it, we will use a <strong><em>var</em></strong> of the same type to access this fetched results controller instance. With this, we will only initialize the controller at the moment that var will be used, similiar to a lazy aproach. The benefits of this are that we guarantee the instance will be initialized at the moment it will be used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27a969b33f7f5760f166dd9b3cf5121b/href">https://medium.com/media/27a969b33f7f5760f166dd9b3cf5121b/href</a></iframe><p>And whenever a change occurs, the fetched results controller will call the method <strong>controllerDidChangeContent:</strong> from his delegate.</p><p>Go ahead, include the method and call the reload data from the table view variable to refresh his data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7256fabd28b901dcb4f5a26e99cb8a6/href">https://medium.com/media/f7256fabd28b901dcb4f5a26e99cb8a6/href</a></iframe><p>Now let’s implement the Table View methods, on the <em>ViewController.swift</em> file, to populate data into it:</p><ul><li>First the Table View will ask how many sections our data contains.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39d063cf00590cc24aa2226fcf7c18fb/href">https://medium.com/media/39d063cf00590cc24aa2226fcf7c18fb/href</a></iframe><ul><li>Then the number of rows for each section.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96d4b63297a2de2edf98a36f74fb247f/href">https://medium.com/media/96d4b63297a2de2edf98a36f74fb247f/href</a></iframe><ul><li>And the updated cell for each object.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/077f138b72a6986f93c86b53f19039d7/href">https://medium.com/media/077f138b72a6986f93c86b53f19039d7/href</a></iframe><p>One thing to note here, after we set the fetched results controller, despite where a change to the Core Data is made, this view controller will react to all changes that may affect the data existent on this fetched results controller that matches the defined filter\predicate.</p><p>At this point, if you run the application, you will only see the user interface that we have created before. So, to see some magic happening, let’s go back to the <strong>addTask:</strong> method, on the <em>ViewController.swift</em> file, and update with the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d42a2ec4b3bafad021022b07b3417ee/href">https://medium.com/media/7d42a2ec4b3bafad021022b07b3417ee/href</a></iframe><p>For editing and deleting, we will implement the optional delegate method the Table View has to offer. Include the following code into the ViewController.swift</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/727c2bb6bf3337573260c5098db60844/href">https://medium.com/media/727c2bb6bf3337573260c5098db60844/href</a></iframe><p>And with this we have successfully setup all stacks of the Core Data framework, with creation, edition and deletion using a basic model layer and a basic user interface. Many thanks for reading!</p><p>The final project can be found on the following link:</p><p><a href="https://github.com/filipemsmartins/MyTasks">filipemsmartins/MyTasks</a></p><p><em>If you have any question or feedback about this article, feel free to leave a comment bellow!</em></p><p><em>Data persistence is always important for any application. There are so many tools we use for this purpose, but as an iOS Developer, this is one of my favourite, and I use it almost on every project.</em></p><p><em>I work at </em><a href="https://www.runtime-revolution.com/"><em>Runtime Revolution</em></a><em> where I build mobile products for our clients, using this framework and so many others.</em></p><p><a href="http://www.runtime-revolution.com/">Runtime Revolution</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc6e0ce844a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runtime-revolution/core-data-on-ios-10-a-brief-overview-with-an-example-dc6e0ce844a5">Core Data on iOS 10, a brief overview with an Example</a> was originally published in <a href="https://medium.com/runtime-revolution">Runtime Revolution</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>