<?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 Michael Gachet on Medium]]></title>
        <description><![CDATA[Stories by Michael Gachet on Medium]]></description>
        <link>https://medium.com/@6Be?source=rss-7c87a5c46111------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MQyWygKqNzEYk3yY.jpeg</url>
            <title>Stories by Michael Gachet on Medium</title>
            <link>https://medium.com/@6Be?source=rss-7c87a5c46111------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 23:24:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@6Be/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[Our Favorite Xcode Shortcuts]]></title>
            <link>https://medium.com/bpxl-craft/our-favorite-xcode-shortcuts-d3271c481d56?source=rss-7c87a5c46111------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3271c481d56</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Michael Gachet]]></dc:creator>
            <pubDate>Mon, 30 Jan 2017 20:43:13 GMT</pubDate>
            <atom:updated>2017-03-24T18:55:47.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OAyLY5-saWo8O6xdhucaw.png" /></figure><p>We recently had a conversation in our developer channel on Slack about our favorite Xcode keyboard shortcuts. This colorful exchange led to the interesting realization that:</p><ol><li>Most of our favorite Xcode shortcuts deal with efficient code navigation and editing.</li><li>Each one of us learned at least one shortcut we did not know existed.</li></ol><p>This last point nudged us into writing this article to share the Xcode shortcuts that we feel best help boost our productivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rl1VunoAQ8k_cfXQ." /><figcaption>A refresher on Xcode’s different areas.</figcaption></figure><p>Our favorite shortcuts focus on three key areas:</p><ul><li>The navigator area on the left where you can see your file structure.</li><li>The editor area in the center where code editing takes place.</li><li>The utilities area on the right where you can further inspect your files or UI.</li></ul><p>Some of the editor area shortcuts deal with the jump bar at the top of the editor itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PXm16-DotrSF75tu." /></figure><h3>1. Edit all in scope: CTRL+⌘+E</h3><p>This shortcut allows you to change the name of a variable or function and have that change take effect in your entire file. Here is an illustration:</p><p><em>Before</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/0*rLZ0V8CMFJ35Xo9A." /></figure><p><em>After</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/0*J8O4IDID39F2FP4y." /></figure><p>We simply clicked on `label` within the `set` method, typed ⌘+CTRL+E, and changed the name to `titleLabel`.</p><h3>2. Fix all in scope: CTRL+⌥+⌘+F</h3><p>This one is a handful, but it’s super handy. It will allow Xcode to automatically fix all errors that can be fixed automatically.</p><h3>3. Open quickly: ⇧+⌘+O</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*1MnNs73L3H1999BEL74WPw.gif" /></figure><p>Type ⇧+⌘+o and start typing in the search box that opens. The strength of “open quickly” is that the search engine is able to discern which files or functions you’re looking for even if you only enter parts of the name. For example, typing “appfinish” will bring up “applicationDidFinishLaunching” as part of the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VAX4ELEDt9ADcjTi." /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/0*n3MOnuedngZTvpfX." /></figure><h3>4. Searching within a file: CTRL+6</h3><p>This powerful shortcut opens the jump bar so you can see all existing symbols in the open file and search for the symbol you are looking for. Let’s look at an example of how it works.</p><p>Here is the jump bar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZTJOPBh54A1AN3Ig." /></figure><p>Type CTRL+6:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GaEtod3OtNf1vmDB." /></figure><p>Here’s where you type the name of the symbol you are looking for:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*uBEkqerMBLPMTLWl." /></figure><p>To make this shortcut more powerful, use CTRL+1–6 to open any part of the navigation hierarchy and start searching through it.</p><h3>5. Jumping to a symbol definition</h3><p>There are two ways to jump to a symbol definition:</p><ul><li>⌘+Click on the symbol to jump to its definition in your current editor window.</li><li>⌘+⌥+Click on the symbol to open the symbol definition file in the assistant editor.</li></ul><p>Below is the result of ⌘+⌥+Click on the `super.viewDidLoad()` symbol in our main editor. It opened the assistant with the `super` class definition of `viewDidLoad()`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YZM5jZBMqc2f3B2C." /></figure><h3>6. Open in…</h3><p>Use ⌥+⇧ with any file or symbol action to bring up an “Open in…” UI and choose where to open this file or symbol.</p><p>For example, performing ⌘+CLICK+⌥+⇧ on a symbol will bring up the following UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/0*q57Hnn8lN_ATqBCp." /></figure><h3>7. Switching assistant editor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*TQAKZm7X-aSMvn_9kfB5JA.gif" /></figure><p>Since we just saw how to open a symbol in the assistant editor, here are three shortcuts to rapidly switch the editor:</p><ul><li>⌘ + Enter opens the standard editor (single window).</li><li>⌘ + ⌥ + ENTER opens the assistant editor.</li><li>⌘ + ⌥ + ⇧ + ENTER opens the source control editor.</li></ul><h3>8. ⌘+⇧+J</h3><p>In a typical project hierarchy it can be easy to lose track of where you are in your file tree structure. ⌘+⇧+J will help you by highlighting the file you are currently editing.</p><h3>9. ⌘+0</h3><p>Use ⌘+0 to toggle the navigator visibility and ⌘+1–8 to switch to any of the navigator tabs.</p><h3>10. ⌘+⌥+0</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*h1a7ZJSTjt_1UGN5kejLHA.gif" /></figure><p>The utilities area can be easily hidden or shown using ⌘+⌥+0. Add ⌘+⌥+1–3 to open one of the utilities tabs.</p><h3>11. ⌘+⇧+⌥+K</h3><p>If you are working with Swift and indexing or Source Kit is causing you grief a fast way to nuke your index and target resources is to use ⌘+⇧+⌥+K. This is the last step before removing your derived data folder.</p><p>We hope you find these shortcuts as useful as we do. Some of them, once discovered, are never forgotten. Others take a bit of time to get used to. Let us know what you think and share your favorite Xcode shortcuts with us in the comments.</p><p><em>For more insights on design and development, subscribe to </em><a href="http://medium.com/bpxl-craft"><em>BPXL Craft</em></a><em> and follow Black Pixel on </em><a href="https://twitter.com/blackpixel"><em>Twitter</em></a><em>.</em></p><p><em>Black Pixel is a creative digital products agency. Learn more at </em><a href="http://blackpixel.com/"><em>blackpixel.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3271c481d56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bpxl-craft/our-favorite-xcode-shortcuts-d3271c481d56">Our Favorite Xcode Shortcuts</a> was originally published in <a href="https://medium.com/bpxl-craft">BPXL Craft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The iOS Huddle #4]]></title>
            <link>https://medium.com/bpxl-craft/the-ios-huddle-4-fc3395945272?source=rss-7c87a5c46111------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc3395945272</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[huddles]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Michael Gachet]]></dc:creator>
            <pubDate>Thu, 29 Dec 2016 20:27:07 GMT</pubDate>
            <atom:updated>2016-12-29T20:27:07.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAgieqlMMYo2_Jclo7aXxQ.png" /></figure><p><strong>Thursday, December 29, 2016</strong></p><p><em>The iOS Huddle is our monthly roundup of the best links shared in the Black Pixel iOS team’s Slack channel.</em></p><h4>Reactive Programming</h4><p>Reactive programming seems to be all the rage these days. If you’re curious about reactive programming, we thought <a href="https://www.cocoawithlove.com/blog/reactive-programming-what-and-why.html">this article from Cocoa with Love</a> was a very good introduction to some of the concepts behind it. Matt Gallagher defines reactive programming by the following principle:</p><blockquote>Any “getter” for mutable state causes problems. Instead of using getters, any calculated, generated, loaded or received state values should be immediately sent into a channel and any part of the program that wants access to these values must subscribe to the channel.</blockquote><p>The article makes some very good points regarding how heavy KVO can be for some simple use cases and outlines some typical issues we’ve all encountered using it. As always, reactive programming may not be the magic cure, but it offers a different way to look at how to design apps.</p><h4>GitHub</h4><p>GitHub now allows you to <a href="https://github.com/blog/2293-resolve-simple-merge-conflicts-on-github">resolve merge conflicts</a> directly from your PR. For the simplest issues, this is a real time saver. For more complex issues, <a href="http://www.kaleidoscopeapp.com/">Kaleidoscope</a> is still our favorite.</p><h4>Meta-Programming</h4><p>DRY is a good concept that’s not often so easy to implement. Some consider DRYing too soon akin to premature optimization. Others swear by it. However you feel about DRY, one thing we may all agree on is that implementation of boilerplate code can be tedious, repetitive, and error prone. I’m looking at you, JSON serialization and NSCoding! So why not replace some or all of this with some nice meta-programming and automated code generation. That’s what <a href="https://github.com/krzysztofzablocki/Sourcery">Sourcery</a> can do for you.</p><h4>Can You Have a Look at This Crash Report?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*trBGe1I7C_G96kd5BPm1Bg.png" /></figure><p>How many of us have been asked this question and handed over an unsymbolicated stack trace? Not much fun. Fortunately Apple has written a very nice technical note titled, “<a href="https://developer.apple.com/library/content/technotes/tn2151/_index.html#//apple_ref/doc/uid/DTS40008184-CH1-SYMBOLICATE_WITH_ATOS">Understanding and Analyzing Application Crash Reports</a>.”</p><h4>Fast Playgrounds</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*lJsEL6Kkt1RQzXsqCvQBhw.png" /></figure><p>Swift Playgrounds can really help with rapid prototyping and testing of ideas. Playgrounds can also be used to isolate some specific issues. <a href="https://github.com/insidegui/PlayAlways">PlayAlways</a> allows you to quickly create Xcode playgrounds right from your menu bar.</p><h4>A Look Behind the Scenes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xq_N9Agvil3fFquMAXQdUA.png" /></figure><p>When Instagram presents how it redesigned its feed, going deep into implementation details, you know you’re likely to learn something. This <a href="https://realm.io/news/tryswift-ryan-nystrom-refactoring-at-scale-lessons-learned-rewriting-instagram-feed/">presentation by Instagram Software Engineer Ryan Nystrom</a> does not disappoint. It’s a must see for anyone curious or eager to perfect their craft.</p><h4>Try? vs. As?</h4><p>This is <a href="http://ericasadun.com/2016/12/15/unexpected-precedence-issues-with-try-and-as/">clear and short article by Erica Sadun</a> that outlines how mixing a try? with as? and conditional binding can have unintended consequences.</p><h4>Where is My Memory?</h4><p>If, like us, you’re an avid reader of Mike Ash’s <a href="https://mikeash.com/pyblog/">in-depth technical blog</a>, you’ll be delighted by his <a href="https://gotocon.com/cph-2016/presentations/show_talk.jsp?oid=7748">GOTO 2016 conference presentation</a>: an exploration of Swift memory layout.</p><h4>Make This Text Larger, Please</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*88d0aq37LgXXSoVa5hWlZg.png" /></figure><p>iOS 7 introduced a completely new visual design paradigm for iOS apps. <a href="https://developer.apple.com/ios/human-interface-guidelines/visual-design/typography/">Dynamic Type</a> was part of that change. This <a href="http://blog.stablekernel.com/supporting-accessibility-larger-text-in-ios">article by Jesse Black at Stable Kernel</a> is a good introduction to Dynamic Type and is a must read for anyone interested in making apps more accessible, even with custom fonts.</p><h4>Gitignore</h4><p>Finally, for those among us who like to keep their repos clean we found <a href="https://github.com/github/gitignore">this nice gem for gitignore templates</a>.</p><p><em>For more insights on design and development, subscribe to </em><a href="http://medium.com/bpxl-craft"><em>BPXL Craft</em></a><em> and follow Black Pixel on </em><a href="https://twitter.com/blackpixel"><em>Twitter</em></a><em>.</em></p><p><em>Black Pixel is a creative digital products agency. Learn more at </em><a href="http://blackpixel.com/"><em>blackpixel.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc3395945272" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bpxl-craft/the-ios-huddle-4-fc3395945272">The iOS Huddle #4</a> was originally published in <a href="https://medium.com/bpxl-craft">BPXL Craft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NSFetchedResultsController Woes]]></title>
            <link>https://medium.com/bpxl-craft/nsfetchedresultscontroller-woes-3a9b485058?source=rss-7c87a5c46111------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a9b485058</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[core-data]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Michael Gachet]]></dc:creator>
            <pubDate>Thu, 11 Aug 2016 16:14:35 GMT</pubDate>
            <atom:updated>2017-05-25T18:52:24.428Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUAMWe_49O4YOcpik1oQjQ.png" /></figure><blockquote>Editor’s Note: This article was first published prior to the release of iOS 10. Apple has since made considerable changes to CoreData: NSPersistentContainer can now be used as a standard Core Data stack.</blockquote><blockquote>Another change that you may have noticed is the fix to the long-standing issue with the NSFetchedResultsController described in this article.</blockquote><blockquote>While the adoption rate of iOS is high, some devices are still running versions of iOS 9 where the NSFetchedResultsController issue is present. Therefore, this article remains relevant to iOS developers today.</blockquote><h4>NSFetchedResultsController</h4><p>NSFetchedResultsController is a staple of iOS Core Data development. Introduced in iOS 3, this class is responsible for efficiently managing collections of Core Data entities.</p><p>Over the last six years, I have used this controller in all my projects with <a href="https://medium.com/bpxl-craft/thoughts-on-core-data-stack-configurations-b24b0ea275f3">various types of Core Data stack configurations</a>. On a recent project for one of Black Pixel’s top clients, we decided to use a standard “sibling” Core Data stack configuration:</p><ul><li>An<em> </em>NSFetchedResultsController was used to fetch objects from the store on the main UI context. This main context was only used for reading from the store.</li><li>The background context, used to retrieve entities from a server, was connected to the persistent store coordinator as a sibling to the main UI context.</li><li>The main context was set up to merge changes from the background context automatically whenever the background context saved its changes to the store.</li></ul><p>Much to my surprise I ended up facing strange issues whereby the NSFetchedResultsController would sometimes be out of sync with the content of the store: Some existing entities matching the NSFetchedResultsController’s predicate would never get fetched.</p><p>How could something so basic and expected be occurring?</p><h4>A Few Explanations and Fixes</h4><p>A quick Google search yielded a bunch of answers. One in particular provided a detailed explanation of <a href="http://stackoverflow.com/questions/16296364/nsfetchedresultscontroller-is-not-showing-all-results-after-merging-an-nsmanage?lq=1">how things played out with the </a><a href="http://stackoverflow.com/questions/16296364/nsfetchedresultscontroller-is-not-showing-all-results-after-merging-an-nsmanage?lq=1">NSFetchedResultsController</a>. Here is the explanation that was given (Note: FRC = NSFetchedResultsController):</p><blockquote><em>1. An FRC is set up with a predicate that doesn’t match all objects (thus preventing the objects that do not match the predicate from being registered in the FRCs context).</em></blockquote><blockquote><em>2. A second context makes a change to an object, which means that it now matches the FRC’s predicate. The second context is saved.</em></blockquote><blockquote><em>3. The FRC’s context processes the </em><em>NSManagedObjectContextDidSaveNotification but only updates its registered objects. Therefore, it does not update the object that now matches the FRC predicate.</em></blockquote><blockquote><em>4. The FRC does not perform another fetch when there’s a save, therefore it isn’t aware that the updated object should be included.</em></blockquote><p>I was bothered by the statement made in the third point.</p><p>Here is the proposed fix:</p><blockquote><em>The solution is to fetch all updated objects when merging the notification.</em></blockquote><p>The idea is to call refreshObject(_:mergeChanges:) on every updated object that is part of the NSManagedContextDidSaveNotification userInfo payload.</p><p>Another set of explanations (for example, articles “<a href="http://www.mlsite.net/blog/?p=518">Core Data Gotcha</a>” and “<a href="http://stackoverflow.com/questions/3923826/nsfetchedresultscontroller-with-predicate-ignores-changes-merged-from-different?lq=1">NSFetchedResultsController with predicate ignores changes merged from different NSManagedObjectContext</a>”) mention that when the NSManagedContextDidSaveNotification<em> </em>is fired, some objects may be faults in the main context and these faults need to be fired before calling mergeChangesFromContextDidSaveNotification().</p><p>The idea here is to call willAccessValueForKey(nil) on every updated object that is part of the NSManagedContextDidSaveNotification userInfo payload. And then call mergeChangesFromContextDidSaveNotification().</p><h4>Time for In-Depth Investigations</h4><p>While in the heat of the project, I settled on the first solution, which introduced a new set of issues that were solved but not always to my satisfaction. I wanted to understand what was going on and verify some of the claims I had been reading that I found disturbing.</p><p>The goals of these investigations are to:</p><ul><li>Figure out what is really going on when changes are merged from one context to another: What is in the target context, and what is in the notification payload?</li><li>Figure out under which conditions is the NSFetchedResultsController fail to behave as one would expect.</li><li>Evaluate the various proposed solutions.</li></ul><h3>Investigation Setup</h3><p>The investigations are performed using a stand-alone iOS application, which is set up as follows:</p><h4>Core Data Stack</h4><p>The Core Data stack is a very basic “sibling” stack with:</p><ul><li>A main context (MainQueueConcurrencyType) that is used as a read-only context.</li><li>A background context (PrivateQueueConcurrencyType) that is read-write.</li></ul><p>The main context and background context are siblings and both are connected directly to the NSPersistentStoreCoordinator. When changes are saved on the background context, they are automatically merged in the main context using the mergeChangesFromContextDidSaveNotification() method.</p><h4>Core Data Model</h4><p>We use a very simple model containing a single entity TestDummy with three properties: id: Int, name: String, isEven: Bool.</p><h4>UI and Main View Controller</h4><p>We have a single view controller that has access to both contexts in the Core Data stack and allows one to:</p><ul><li>Insert, update, and delete objects in the background context.</li><li>Save both the main and background contexts.</li><li>Display information about objects present in both contexts as fetched by two instances of NSFetchedResultsController.</li></ul><p>The controller also allows for controlling how the NSManagedObjectContextDidSaveNotification notifications received on the main context are to be processed. Nothing other than mergeChangesFromContextDidSaveNotification() occurs by default.</p><h4>NSFetchedResultsController</h4><p>Two instances of FRC are managed by the main view controller:</p><ul><li>One instance fetches all TestDummy objects in the main UI context. This instance is referred to the “main FRC.”</li><li>One instance fetches all TestDummy objects in the background context. This instance is referred to the “background FRC.”</li></ul><p>The main context FRC can use two predicates to either fetch all TestDummy entities or only those marked as isEven == true.</p><h3>Let’s Fetch Them All!</h3><p>We start by setting up the main FRC to fetch all TestDummy entities, and we look at three different scenarios taking place in the background context: inserting, updating, and deleting.</p><h4>Inserting Objects</h4><p>We performed the following simple test:</p><ol><li>Inserting four entities in the background context.</li><li>Saving the background context.</li></ol><p>The insertion leads to the following:</p><ol><li>The content of the insertedObjects property on the background context before <em>save</em> matches the content of the registeredObjects property.</li><li>The objects fetched by the background FRC match the registeredObjects set.</li></ol><p>As expected, s<em>aving</em> changes made in the background context pushes all those changes to the main context:</p><ol><li>The content of the registeredObjects on both the main and background contexts should be identical.</li><li>The objects fetched by the main FRC match the registeredObjects set in the main context.</li><li>The main FRC informs its delegate that insertions took place.</li></ol><p>As a side note, saving the background context also resets the insertedObjects set to nil on that context.</p><h4>Updating Objects</h4><p>Understanding what happens when updating objects required digging a bit deeper and looking at two alternate scenarios:</p><p><strong>Scenario #1</strong></p><ol><li>Inserting four entities in the background context.</li><li>Updating entities 0 and 2 by changing their isEven (from false to true) and title properties.</li><li>Saving the background context.</li></ol><p><strong>Scenario #2</strong></p><ol><li>Inserting four entities in the background context.</li><li>Saving the background context.</li><li>Updating entities 0 and 2 as before.</li></ol><p><strong>Results</strong></p><p>As far as Core Data is concerned, objects that have been <em>inserted</em> and then <em>updated</em> before saving the background context are considered as <em>inserted</em>. This means that if you inspect the background context’s updatedObjects set, it will be empty by the time you are notified of the changes (it will <em>not</em> be empty right after the update). This may be expected, but it surprised us nonetheless.</p><p>The second scenario was much more straightforward. Since the objects have been saved <em>before</em> being updated, they will appear in the updatedObjects set of the background context. This is in line with what one would expect.</p><p>Once again the main FRC behaves as expected: It fetches all entities and properly notifies its delegate.</p><h4>Deleting Objects</h4><p>For deletion we also needed to look into two different scenarios. However, the case of deletion is not as interesting as insertion and updating, as far as the main FRC is concerned. Indeed if an object is registered in the main context, the FRC will always react to this object being deleted.</p><p>The most interesting findings are:</p><ul><li>Deleting objects from the background context before ever saving that context will remove these objects from the deletedObjects set, and the insertedObjects set will contain the net difference between what was inserted and what was deleted.</li><li>Deleting objects after saving changes will bring these objects into the deletedObjects set as one would expect.</li><li>The contents of the registeredObjects and deletedObjects set on the background context may reflect a transient state during the <em>save</em> and should therefore be used with care.</li><li>The main context will contain all changes made to the background context (i.e., the registeredObjects set will contain all objects before deletion, and the deletedObjects set will contain the deleted objects).</li><li>Once again, the main FRC reacts properly to all changes.</li></ul><h4>Conclusions and Insights</h4><p>If the delegate of the FRC is not set:</p><ul><li>The fetchedObjects<em> </em>array will only contain the objects resulting from the initial fetch.</li><li>The FRC does not receive notifications when objects change or when the context it initialized with is saved.</li></ul><p>If the delegate is set for the main FRC, it behaves exactly as expected for entities matching the FRC’s fetch request:</p><ul><li>Objects inserted, updated, or deleted in the background context are properly fetched (deleted) when the background context merges its changes into the main context.</li><li>Deletions of permanent objects (i.e., saved to the store and with a permanent objectID) in the background context are carried over to the main context for objects registered in the main context.</li></ul><p>However, these tests are very specific: The main FRC<em> </em>is set up to fetch all TestDummy entities, which is rarely the case in a real application.</p><h3>Let’s Only Fetch a Subset!</h3><p>In order to reflect something more realistic, we perform the same tests as before with one slight change. The main FRC is now set up to only fetch TestDummy entities that are marked as isEven == true. Let’s see what happens.</p><p>When entities are inserted in the background context the isEven property is set to <em>false</em>. Therefore, after inserting objects in the background context and saving them, no entities will be fetched by the main FRC. But what happens if:</p><ul><li>We insert entities that match the main FRC’s predicate?</li><li>We update some entities to match the main FRC’s predicate<em>?</em></li></ul><h4>Inserting Matching Entities</h4><p>When entities inserted in the background context are such that they match the main FRC, they will be properly fetched by this FRC when the background context is saved.</p><h4>Updating Entities to Match the Main <em>FRC’s Predicate</em></h4><p>This case is more troublesome. As we stated previously, updating an entity will behave differently depending on whether this entity has already been saved or not:</p><ul><li>If the entities are inserted in the background context, updated to match the main FRC’s predicate, and then saved, the main FRC will fetch those entities. All behave as if those entities had been inserted to match the predicate in the first place.</li><li>On the other hand, if entities are inserted, saved, and then updated to match the main FRC’s predicate, <strong>they will never be fetched by the main FRC</strong>.</li></ul><h4>Looking at Potential Solutions</h4><p>We can think of four different ways of addressing this issue and will discuss each separately in this section.</p><h4>Changing the Stack Configuration</h4><p>Remember that this issue applies to configuration where changes made in the background context are pushed to the persistent store coordinator and subsequently merged into the main context.</p><p>Switching to a configuration where the background context writes its changes to the main context instead will eradicate this issue with the FRC. This would be a radical approach to solving this issue. Indeed, reconfiguring the stack to a “parent-child” configuration is a radically different architectural approach to change management and comes with a few caveats:</p><ul><li>The “parent-child” configuration results in a lot more traffic through the main context. All <em>fetch</em> and <em>save</em> operations will block the main context while they occur.</li><li>You need to deal with temporary object IDs until objects are saved to the persistent store. Alternatively, you may request permanent object IDs when inserting objects in the background context. But again, this comes at the price of some performance.</li><li>You have less control over merging in case of conflicts between what is in the background context and what is in the main context.</li></ul><h4>Refreshing Objects in the Main Context</h4><p><strong>Typical Implementation<br></strong>The idea is to call refreshObjects(mergeChanges:) for updated objects when processing the NSManagedObjectContextDidSaveNotification notification payload on the main context.</p><p>Implementations usually refresh all updated objects in the notification payload.</p><p><strong>Benefits</strong></p><ul><li>Simple to implement.</li><li>Centralized implementation in an NSManagedContext extension is possible.</li><li>We can choose to fault (mergeChanges = false) or merge (mergeChanges = true).</li></ul><p><strong>Drawbacks</strong></p><ul><li>We need to call this method on each individual object, with each call resulting in an update of the FRC. This could easily create a performance bottleneck. Any updated objects that were previously registered with the FRC will be updated twice.</li><li>With mergeChanges = false, we fault all refreshed objects in the main context. If those objects are referenced by the FRC, the faults will immediately fire. This results in at least three updates of the complete set of objects fetched by the FRC that have been updated: once as part of the default FRC update mechanism, once due to the forced refresh, and once when faults are immediately fired.</li><li>Still, with mergeChanges = false, faulting existing objects in the context can have nasty side effects. All relationships are faulted, meaning that any reference to those faulted objects or any of the objects they relate to will become invalid. This can easily become pretty hard to manage efficiently. And the last thing you want is a reference to a dead managed object that will crash your application when you try to access it.</li><li>With mergeChanges = true, you will keep existing objects in memory but override any changes with values from the persistent store (i.e., the background context in that case). If you take the strong approach of making your main context read-only, by enforcing that all changes be applied to the background context exclusively, this may work.</li><li>We need to choose whether to set mergeChanges = false or mergeChanges = true.</li></ul><p><strong>Typical Example of NSManagedObjectContext Extension and Usage</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90339c53cf58d292447ab1b29704ed4f/href">https://medium.com/media/90339c53cf58d292447ab1b29704ed4f/href</a></iframe><h4>Improving on refreshObject(_, mergeChanges:)</h4><p>The main drawback of a global implementation that indiscriminately refreshes all updated objects on the main context is that it will refresh objects that are perfectly well managed by the main FRC.</p><p>One obvious way to use the same mechanism in a more refined manner is to have the FRC register for the NSManagedObjectDidSaveNotification<em> </em>directly. By doing so, we are able to limit our refresh call to objects that:</p><ul><li>Are not already registered with the main context.</li><li>Match the FRC’s fetchRequest properties (i.e., its entity and predicate, if defined).</li></ul><p><strong>Benefits</strong></p><ul><li>Simple implementation within an NSFetchedResultsController<em> </em>extension.</li><li>Ability to target refreshing objects that are not registered and that are specific to the FRC only.</li><li>Better performance for refreshing.</li><li>No faulting of objects that are not related to the FRC and that are already registered in the main context.</li></ul><p><strong>Drawback</strong></p><p>At the point where the main FRC registers for saves on the background context, knowledge of the background context is required. If you want to hide this context from your application, it may be an option to vend FRC from your core data stack directly or whichever class has access to both contexts.</p><p><strong>Sample NSFetchedResultsController Extension</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5114ede58b5e26c60ea9d2ff30159a1/href">https://medium.com/media/c5114ede58b5e26c60ea9d2ff30159a1/href</a></iframe><p>The idea behind this extension is:</p><ol><li>Tell each FRC to monitor saves made to a specific context (typically, the background context).</li><li>Upon receiving an NSManagedObjectContextDidSaveNotification for the observed context, check whether this FRC’s predicate filters out entities or not. If not, don’t do anything. The FRC will work as expected.</li><li>Retrieve all inserted and updated entities from the notification payload, and only save the objectID of the objects matching the FRC’s entity and predicate<em>.</em></li><li>From this set of objects, remove all objects that are already registered with the FRC’s context. Being registered, these objects will be managed properly by default.</li><li>Each remaining object is newly inserted in the monitored context and not yet registered in the FRC: call refreshObject(_, mergeChanges:false). Setting mergeChanges:false works perfectly: The object is non-existent in the FRC’s context and the faulting will have no side effects.</li></ol><h4>Calling willAccessValueForKey(nil)</h4><p>Another typical solution seen on Stack Overflow is to replace the call to refreshObjects(_, mergeChanges:) by a call to willAccessValueForKey(nil) to fault all new objects in the context, and then call mergeChangesFromContextDidSaveNotification() if required.</p><p>Once again, this method is called for all updatedObjects that are part of the notification payload received by the main context while processing the NSManagedObjectContextDidSaveNotification notification. As per Apple documentation:</p><blockquote><em>You can invoke this method with the key value of nil to ensure that a fault has been fired.</em></blockquote><p>Implemented globally, this method will suffer from the same drawback as the previous method. Implemented for only targeted objects, using an NSFetchedResultsController<em> </em>extension works fine. Here is an example of such an extension implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0bcf96a57ff4e536e01b134ceaab3d3/href">https://medium.com/media/a0bcf96a57ff4e536e01b134ceaab3d3/href</a></iframe><p>You could call this method instead of the previously defined processChangesWithRefreshObject(_, mergeChanges:). Once again, there should be no side effects to calling this method. We only fault objects that are brand new to the main context and matching the main FRC’s <em>predicate</em>.</p><h4>Refetching Objects When Changes Occur</h4><p>This is an idea that you may be tempted to implement. It consists of monitoring changes to the background context using the same NSManagedObjectContextDidSaveNotification<em> </em>notification and call performFetch() whenever required.</p><p>We implemented this method to see whether it worked or not, because we identified refreshing all objects at once as more preferable than one at a time.</p><p>However, we discovered a huge drawback to using this method: The FRC’s delegate is <strong>never</strong> notified of the changes. The new objects are being fetched and registered in the main context, but no one knows about them.</p><p>One way to work around this issue is to call the delegate methods ourselves after the call to performFetch. This is easy enough as long as changes do not affect the FRC’s sections. At that point, the work required starts to look a lot like a reimplementation of the FRC’s main feature of change tracking, which is not a wise thing to do.</p><h3>To Conclude</h3><p>For a sibling stack configuration (main context and private queue context connected to the persistentStoreCoordinator) prior to iOS 10:</p><ul><li>An NSFetchedResultsController fetching objects in the main context will only be able to fetch objects inserted in the background context if, at the time of saving the background context, the inserted objects match that NSFetchedResultsController’s predicate<em>.</em></li><li>If no predicate exists, the NSFetchedResultsController will behave as expected, fetching all relevant entities inserted in the background context.</li><li>If a predicate exists, the NSFetchedResultsController will only fetch objects inserted in the background context if, and only if, they match that predicate at the time the objects are first saved in the background context.</li><li>If changes are made after the first save, the updated objects will <strong>never</strong> be fetched if they were not already registered in the main context.</li><li>Saving objects in the background context and merging changes in the main context behaves as documented at the end of the current run loop.</li><li>Calling refreshObject(_:mergeChanges:) on all updated objects when processing NSManagedObjectDidSaveNotification notification payload coming from the background context, the solution most often proposed on Stack Overflow, is both inefficient and rife with issues related to faulting.</li><li>By contrast, calling this same method on an NSFetchedResultsController extension that allows an NSFetchedResultsController’s instance to monitor changes made to the background context works extremely well and results in no undesirable side effects that we could identify.</li></ul><h3>The Way Forward</h3><p>Apple fixed a long-standing issue impacting NSFetchedResultsController<em> </em>with the release of iOS 10. For most recent applications, this issue is now a thing of the past. However, some projects can still benefit from the insights presented in this article. With WWDC around the corner, we are very excited to see what new changes Apple brings to Core Data.</p><p>For more insights on design and development, subscribe to <a href="http://medium.com/bpxl-craft">BPXL Craft</a> and follow Black Pixel on <a href="https://twitter.com/blackpixel">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a9b485058" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bpxl-craft/nsfetchedresultscontroller-woes-3a9b485058">NSFetchedResultsController Woes</a> was originally published in <a href="https://medium.com/bpxl-craft">BPXL Craft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WWDC 2016 Spotlight: iOS 10 Animations]]></title>
            <link>https://medium.com/bpxl-craft/wwdc-2016-spotlight-ios-10-animations-af84a273e691?source=rss-7c87a5c46111------2</link>
            <guid isPermaLink="false">https://medium.com/p/af84a273e691</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[wwdc]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Michael Gachet]]></dc:creator>
            <pubDate>Thu, 07 Jul 2016 19:55:59 GMT</pubDate>
            <atom:updated>2016-07-12T23:53:32.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVl_r6GTNFJGfQ4OFRxfFA.png" /></figure><p>Incorporating animations into apps makes for an immersive experience and helps alert the user when there’s something they should pay attention to. In previous versions of iOS, UIKit view animations were fire-and-forget. You would specify a duration, some options and a few animations, and iOS would take care of running the animations for you. There was no way to change these animations or their timing, query their progress or pause them. You fired the animation and forgot about it.</p><p>At WWDC this year, we were excited to learn that these limitations would fall away with iOS 10 and a new API to manage animations will be available. Using the <strong>UIPropertyViewAnimator</strong> class, we will be able to have complete control over animations in UIKit. This update will allow us to:</p><ul><li>Control timing, switching seamlessly between interactive and automatic transitions.</li><li>Control animations by adding or removing them on the fly as animations are ongoing.</li><li>Stop, pause, or resume an existing animation block.</li></ul><h3><strong>Some Examples</strong></h3><h4><strong>Spinning Ball</strong></h4><p>I’ve often wanted the ability to animate the rotation of a view a certain number of times before stopping. Using the view’s <em>transform</em> property for this is not straightforward: The transform interprets all angles as belonging to [0, 2π], so spinning a view for more than a complete rotation requires decomposing the rotation in π increments and chaining those animations together to produce the desired spinning. With <strong>UIPropertyViewAnimator</strong> this becomes a lot easier. Here is a sample of how this could be done:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a78da05cd9a9701395e494f4059715c2/href">https://medium.com/media/a78da05cd9a9701395e494f4059715c2/href</a></iframe><p>The very interesting part here is the use of additive animations, which allows us to simply add the half-rotation several times to the animator to achieve the total spin.</p><p>More examples can be found in <a href="https://github.com/bpxl-labs/bpxl-animation-samples/tree/UIPropertyViewAnimator/wwdc2016-article">this playground</a>.</p><h4><strong>Interactive Changes</strong></h4><p>We have setup <a href="https://github.com/bpxl-labs/bpxl-animation-samples/tree/UIPropertyViewAnimator/wwdc2016-article">a simple Xcode project</a> to outline some other aspects of the <strong>UIPropertyViewAnimator</strong>. When you compile and run the Xcode project you will see a small ball and the following interactions are possible:</p><ul><li>Tap with one finger to move the ball to the tap location.</li><li>Tap another time during the animation to spin the ball three times.</li><li>Double tap to pause the animation.</li><li>Tap with one finger to resume a paused animation with a new target.</li><li>Tap with two fingers to reverse the current animation.</li></ul><h3>New Era of Animations</h3><p>This is fantastic news for iOS developers going forward and will no doubt usher in a new era of animations in all iOS and tvOS applications. To learn more about animating views, check out <a href="https://developer.apple.com/videos/play/wwdc2016/216/">Advances in UIKit Animations and Transitions</a>.</p><p>For more insights on design and development, subscribe to <a href="http://medium.com/bpxl-craft">BPXL Craft</a> and follow Black Pixel on <a href="https://twitter.com/blackpixel">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af84a273e691" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bpxl-craft/wwdc-2016-spotlight-ios-10-animations-af84a273e691">WWDC 2016 Spotlight: iOS 10 Animations</a> was originally published in <a href="https://medium.com/bpxl-craft">BPXL Craft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WWDC 2016 Spotlight: iOS 10 UICollectionView and UITableView]]></title>
            <link>https://medium.com/bpxl-craft/wwdc-2016-spotlight-ios-10-uicollectionview-and-uitableview-5f1c83140893?source=rss-7c87a5c46111------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f1c83140893</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[wwdc]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Michael Gachet]]></dc:creator>
            <pubDate>Tue, 05 Jul 2016 22:10:24 GMT</pubDate>
            <atom:updated>2016-07-05T22:10:24.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-1BYRT2yEZHyGhJj2VilQ.png" /></figure><p><strong>UICollectionView</strong> and <strong>UITableView</strong> are staples of iOS applications. Each year Apple improves those APIs, and this year the updates announced at WWDC focus heavily on scrolling performance.</p><p>Since its inception, <strong>UITableView</strong> has used a pool of reusable cells, which was limited to the maximum number of cells visible on screen at any time. The table view data source would ask an application for a cell at a specific index path and a cell would be taken from that pool, configured, and returned to the table view. The just-in-time approach to cell dequeuing and configuration may have been fine at a time of static frame computations using springs and struts. With the advent of Auto Layout, <strong>UIStackView</strong>, and automatic sizing of cells, the amount of computing required to configure cells has increased significantly. This made it very easy to run into situations where scrolling would be jerky even on the most powerful iOS device.</p><p>Starting with iOS 10, the pool of available cells has increased. With the increase, more cells will be configured ahead of time when scrolling occurs, which will likely translate into much smoother scrolling. The size of the pool is not yet known. It’s probably regarded by Apple as an implementation detail and is likely to adapt to the current device capabilities.</p><p>The great news for developers is this will require no change at all in existing code, just a recompiling of the source with the iOS 10 SDK. For users, the experience will be that much smoother.</p><p>One last thing for the road: Our dear <strong>UIRefreshControl</strong> is now available for <strong>UICollectionView </strong>… at last!</p><p>For more information on <strong>UICollectionView</strong> and <strong>UITableView</strong>, check out these resources:</p><ul><li><a href="https://developer.apple.com/videos/play/wwdc2016/219/">What’s New in UICollectionView in iOS 10</a></li><li><a href="https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithScrollViews.html#//apple_ref/doc/uid/TP40010853-CH24-SW1">Working With Scroll Views</a></li></ul><p>For more insights on design and development, subscribe to <a href="http://medium.com/bpxl-craft">BPXL Craft</a> and follow Black Pixel on <a href="https://twitter.com/blackpixel">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f1c83140893" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bpxl-craft/wwdc-2016-spotlight-ios-10-uicollectionview-and-uitableview-5f1c83140893">WWDC 2016 Spotlight: iOS 10 UICollectionView and UITableView</a> was originally published in <a href="https://medium.com/bpxl-craft">BPXL Craft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WWDC 2016 Spotlight: Core Data]]></title>
            <link>https://medium.com/bpxl-craft/wwdc-2016-spotlight-core-data-2699e94d35f7?source=rss-7c87a5c46111------2</link>
            <guid isPermaLink="false">https://medium.com/p/2699e94d35f7</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[core-data]]></category>
            <category><![CDATA[wwdc]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Michael Gachet]]></dc:creator>
            <pubDate>Tue, 21 Jun 2016 18:35:34 GMT</pubDate>
            <atom:updated>2016-06-21T18:58:03.797Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQSzzVxXJaC6hfu2-XWTZQ.png" /></figure><p>The launch of <a href="http://www.apple.com/ios/ios10-preview/">iOS 10</a> this fall means advancements for its tools and frameworks, including Core Data. Apple recently unveiled some <a href="https://developer.apple.com/videos/play/wwdc2016/242/">important updates to Core Data</a> that focus on ease of use, safety, and control. Here are some initial thoughts about those changes and how they’ll impact developers.</p><h4><strong>Making Core Data More Accessible</strong></h4><p>The <strong>NSPersistentContainer</strong> class provides a nice full-featured Core Data stack, which is very simple to set up and use. It provides a <strong>viewContext</strong>, which, as the name suggests, is meant to be used by view controllers to manage “visible” model objects. It makes performing operations on a background context easy with the method <strong>performBackgroundTask(_,:)</strong>, which gives developers the managed object context needed to perform those operations. This should significantly remove the barrier to entry for Core Data. It will also make some common operations a lot faster to write by hiding some of the complexities from developers, especially with respect to background context operations.</p><h4><strong>Preventing Concurrency Issues</strong></h4><p>Regarding fetching, the new <strong>NSFetchRequest</strong> class should make using Core Data both easier and safer; it uses generics to create objects of a specific class and has a built-in mechanism to prevent executing a fetch outside of a <strong>performBlock()</strong> or <strong>performBlockAndWait()</strong> closure. This should further reduce concurrency issues with Core Data.</p><h4><strong>Giving Developers More Control</strong></h4><p>On the more advanced side of Core Data, developers will now be able to lock the results of a fetch on a context to a specific version of the data. This means that unless the main context is explicitly saved or merged, its data could remain unchanged and tagged to a specific version of the data all while changes are happening in the background. This will give developers more control over when their view context actually changes.</p><h4><strong>Reading Data from the Store</strong></h4><p>On the performance front, Core Data now allows multiple simultaneous reads and a single write to the data without locking the store and blocking the contexts. In prior versions of iOS, when a context was reading from the store all other contexts had to wait to perform their own read or write. This is longer the case. Now multiple contexts can read data from the store simultaneously. Naturally, only one context at a time can write to the store at a time. In fact, the lock which used to occur at the <strong>NSPersistentStoreCoordinator</strong> is now moved to the SQLite database. This means that some serialization still occurs whenever the SQLite store is hit. In the presentation at WWDC, Apple stated that a net result of this will be a more responsive UI where the view context is able to fetch data while a background context writes data to disk. We are looking forward to this.</p><h4><strong>More Core Data Resources</strong></h4><p>These Core Data developments are exciting as they should make the framework more approachable and performant. If you’d like to know more about getting started with Core Data, check out these resources from our team:</p><ul><li><a href="https://dribbble.com/shots/2697938-Key-Components-of-Core-Data">Key Components of Core Data</a></li><li><a href="https://blackpixel.com/writing/2016/05/how-to-add-core-data-to-a-project.html">How to Add Core Data to a Project</a></li><li><a href="https://medium.com/bpxl-craft/thoughts-on-core-data-stack-configurations-b24b0ea275f3#.ya538la4a">Thoughts on Core Data Stack Configuration</a></li><li><a href="https://medium.com/bpxl-craft/some-lessons-learned-on-core-data-5f095ecb1882#.7iubezo77">Some Lessons Learned on Core Data</a></li><li><a href="https://twitter.com/hashtag/BPXLCoreData?src=hash">Core Data Tips</a></li></ul><p>For more insights on design and development, subscribe to <a href="http://medium.com/bpxl-craft">BPXL Craft </a>and follow Black Pixel on <a href="https://twitter.com/blackpixel">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2699e94d35f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bpxl-craft/wwdc-2016-spotlight-core-data-2699e94d35f7">WWDC 2016 Spotlight: Core Data</a> was originally published in <a href="https://medium.com/bpxl-craft">BPXL Craft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thoughts on Core Data Stack Configurations]]></title>
            <link>https://medium.com/bpxl-craft/thoughts-on-core-data-stack-configurations-b24b0ea275f3?source=rss-7c87a5c46111------2</link>
            <guid isPermaLink="false">https://medium.com/p/b24b0ea275f3</guid>
            <category><![CDATA[core-data]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Michael Gachet]]></dc:creator>
            <pubDate>Mon, 09 Nov 2015 21:09:16 GMT</pubDate>
            <atom:updated>2015-11-09T21:09:16.600Z</atom:updated>
            <content:encoded><![CDATA[<p>This post relies on some prior knowledge of Core Data and the persistence stack. It is based on personal experience with Core Data. If you are new to Core Data, you may want to have a look at my previous article about <a href="https://medium.com/bpxl-craft/some-lessons-learned-on-core-data-5f095ecb1882">lessons learned on Core Data</a> first.</p><h4>A Pretty Good Start</h4><p>There is a Core Data stack configuration that is a very good start and will cover most use cases. It uses two contexts by default:</p><ol><li>A <em>PrivateQueue</em> context, which is connected to the persistence store.</li><li>A <em>MainQueue</em> context, which is a child of the <em>PrivateQueue</em> context and is used to perform all UI operations.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*g8cWfD2Q4LWe96jmnE_lGA.png" /><figcaption>A typical Core Data Stack basic configuration.</figcaption></figure><p>The advantage of this configuration is that the UI context saves all its objects in memory: no latency for saves. And the persistence to disk can be executed asynchronously on the <em>PrivateQueue</em> context: saving does not block the UI.</p><p>This setup is typically abstracted away by wrapping the setup in a persistence controller that you pass around to your view controllers. For a good starting point, have a look at the <a href="http://martiancraft.com/blog/2015/03/core-data-stack/">post by Marcus Zarra on that topic</a>.</p><p>If you work with a networking application you will need to determine which context should be used to import changes from your server. There are two configurations that are very often used.</p><h4><strong>The “B<em>ackground Context as a Sibling</em>” Configuration</strong></h4><p>In this configuration you perform background operations on a context that is a sibling to the main UI context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*6UfMw_vIglltPujlfqNkJg.png" /><figcaption>“Siblings” configuration.</figcaption></figure><p>With this configuration everything you do in the background context is invisible to the main UI context by default and vice versa.</p><p>The most practical way to propagate changes from the background context to the main context in this case is to have the main UI context register as an observer of the<a href="https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/index.html#//apple_ref/c/data/NSManagedObjectContextDidSaveNotification"> <em>NSManagedObjectContextDidSaveNotification</em></a><em> </em>notification.</p><p>Upon receiving this notification you would merge the changes by using a code similar to this, typically in your persistence controller but not necessarily:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb9dd90b90be2b185ad87056e2e5249e/href">https://medium.com/media/cb9dd90b90be2b185ad87056e2e5249e/href</a></iframe><p>Note that if your application uses different Core Data stacks (maybe a third-party analytics package uses one), you will need to be extra cautious about this approach and may have to rely on a different mechanism. For instance, using a custom notification that triggers fetch on your main context to refresh its content.</p><p>The biggest advantage of this stack configuration is that the main thread is isolated from changes made to the background thread until you merge them into the main thread.</p><p>The biggest inconvenience is the merge procedure. As with every merge, there may be conflicts that will need to be resolved by specifying the relevant merge policy on your main context. Which<a href="https://developer.apple.com/library/mac/documentation/CoreData/Reference/NSMergePolicy_Class/index.html#//apple_ref/doc/constant_group/Merge_Policies"> merge policy</a> to use really depends on the application. For example, if the main context is considered “read-only” then <em>MergeByPropertyStoreTrumpMergePolicyType</em> on the main context and <em>MergeByPropertyObjectTrumpMergePolicyType</em> on an import context could be used.</p><h4><strong>The <em>“Background Context as a Child”</em> Configuration</strong></h4><p>In this configuration you perform all background operations on a child of the main UI context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*G6TAPt4mMu8HXjLL_oFHUA.png" /><figcaption>Left: “Sibling” Stack, Right: “Children” Stack.</figcaption></figure><p>The main advantage of this configuration is that all changes made to the background context are automatically saved into the main UI context. There is no need to merge changes as this is done automatically for you. However, this approach is not fail safe and you may still encounter save issues.</p><p>One main drawback of this configuration is the performance impact. All stack operations made from the background context (fetch/add/delete) will transit through the main UI context. If you have <strong><em>many</em></strong> such requests it may significantly impact the work performed by the main thread to process these requests.</p><p>Florian Kugler wrote an interesting post awhile back on the topic of <a href="http://floriankugler.com/2013/04/29/concurrent-core-data-stack-performance-shootout/">core data stack performance</a> if you want to know more.</p><h4>On Background Contexts</h4><p>Consider the following realistic scenario where two network operations are added to a concurrent queue:</p><ul><li>Operation A operates on context A to retrieve objects of type A from the backend.</li><li>Operation B operates on context B to retrieve objects of type B from the backend.</li></ul><p>What will happen if there is a relationship between objects of type A and objects of type B? What will happen when objects in context A are deleted while still regarded as valid in context B?</p><p>Having both operations using two different contexts will most likely lead to crashes that will be very difficult to reproduce, identify, isolate, and fix.</p><p>In such a case it would be a lot safer and easier to use a single background context to perform both networking operations A and B.</p><h4>The Main UI Context</h4><p>Another thing worth thinking about is what should happen to operations using background contexts when a critically important object is deleted by the user in the main UI context?</p><p>Consider the following setup:</p><ul><li>The managed object User can have many managed Post objects. The relationship is one to many.</li><li>After launch, the application starts updating the posts in the background.</li><li>The user logs out or deletes his account while the update is taking place.</li></ul><p>A “naive” way to go about this could be to write something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a2c0d0dc54e615385ea35875343ec29/href">https://medium.com/media/6a2c0d0dc54e615385ea35875343ec29/href</a></iframe><p>I’ve taken this approach many times myself. It makes perfect sense to delete an object directly when you don’t need it anymore. But doing so exposes you to concurrency crashes that are very hard to reproduce.</p><p>A better, albeit imperfect, approach is to mark objects as “deleted” instead of deleting them and defer the actual deletion until later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77c3863f48eea58645e1b12929b3afbf/href">https://medium.com/media/77c3863f48eea58645e1b12929b3afbf/href</a></iframe><p>This code is almost similar to the “naive” one … with the exception that when the user logs out or deletes her account, the corresponding object is merely marked as “deleted.” Proceeding this way is a lot safer than directly deleting objects from the object graph when your application contains several managed object contexts.</p><h4>Contexts and Stale Data</h4><p>When you deal with parent-child contexts, always remember that changes to the parent are not pushed down to its children. This means that the information in the child context may be stale. They may still be holding references to objects that are no longer valid. Be aware of this and devise the proper strategy to deal with it in your application.</p><p>One such strategy could be to keep the background context around for as long as the main UI context exists. In that case it is safest to assume that your objects are stale before making any operation and either:</p><ul><li>Call <em>reset()</em> on your context to clear out any stale objects and reduce memory usage.</li><li>Fetch the objects you need to work with.</li><li>Refresh your context using the <em>refreshObject(: , mergeChanges:)</em> method on <em>NSManagedObjectContext</em>.</li></ul><p>Another strategy is to create a background context on demand, and delete it once it has performed its duty. For instance, you could create a background context at the start of your update sequence and discard it once all updates have completed. Just be aware of the risk inherent to creating many sibling background contexts.</p><h4>There Is so Much More</h4><p>Core Data and concurrency is a vast topic. There can be many different stack configurations (as we were editing this post <a href="https://www.bignerdranch.com/blog/introducing-the-big-nerd-ranch-core-data-stack/">Big Nerd Ranch introduced their Core Data Stack</a>).</p><p>No matter what your stack is you need to really understand it and pay close attention whenever you are dealing with either sibling or parent-child contexts. Neither configuration is foolproof nor fail safe.</p><p>We hope this article shed some light on some very practical and common stacks and the things to keep in mind when dealing with them. If you want to learn even more about this topic, I recommend a book (now in early access) <a href="https://www.objc.io/books/core-data/">by Florian Kugler and Daniel Eggert</a> from objc.io.</p><p>Good luck with your next Core Data project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b24b0ea275f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bpxl-craft/thoughts-on-core-data-stack-configurations-b24b0ea275f3">Thoughts on Core Data Stack Configurations</a> was originally published in <a href="https://medium.com/bpxl-craft">BPXL Craft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some Lessons Learned on Core Data]]></title>
            <link>https://medium.com/bpxl-craft/some-lessons-learned-on-core-data-5f095ecb1882?source=rss-7c87a5c46111------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f095ecb1882</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[core-data]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Michael Gachet]]></dc:creator>
            <pubDate>Wed, 28 Oct 2015 21:26:18 GMT</pubDate>
            <atom:updated>2015-10-28T21:26:51.371Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*3gVOXc-yVWqz8mnnfUXUCw.png" /></figure><p>I’ve been using Core Data since iOS 3.1. I was working on my first application: a weather app providing past weather data as well as long range forecasting for the United States. I did not really need to use Core Data, but I wanted to gain some experience with that framework. Since then I’ve used Core Data in about 90 percent of the projects I’ve worked on.</p><p>Over the years I made <em>many</em> mistakes with Core Data, most of which were related to using multiple contexts and concurrency. Before diving into the things I’ve learned along the way, let’s start with a short primer on Core Data.</p><h4>What is Core Data?</h4><p>You read all sorts of things on the Internet about Core Data, mostly depending on the past experience of whoever writes about it.</p><p>If I were to describe what Core Data is to me, I would say it’s an Apple framework which allows you to:</p><ol><li>Define entities with properties (called attributes) and relationships with other entities (one-to-one, one-to-many, or many-to-many). This is what you do when you create your Core Data model in Xcode.</li><li>Create, delete, retrieve, and, more generally, manage instances of those entities (called managed objects) at runtime.</li><li>Persist those managed objects to memory or disk.</li></ol><h4>The Managed Objects …</h4><p>At runtime the static model entities are used to create instances of <a href="https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObject_Class/index.html#//apple_ref/occ/cl/NSManagedObject"><em>NSManagedObject</em></a> subclasses which are commonly referred to as managed objects. Those managed objects do not exist in a vacuum; they have to exist within a context that is an instance of the <a href="https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/index.html#//apple_ref/occ/cl/NSManagedObjectContext"><em>NSManagedObjectContext</em></a> class.</p><h4>… Live in a Context …</h4><p>The context in which managed objects live can be regarded as a scratch pad in which objects are loaded, modified, created, deleted, and saved.</p><p>When several objects exist within a context they define an object graph <em>in that context</em>. The context is then responsible for managing all objects in this object graph:</p><ul><li>Ensuring the relationships are properly updated whenever an object is added to or deleted from the graph.</li><li>Fetching objects “from storage.”</li><li>Saving objects “to disk.”</li></ul><p>At runtime, any managed object instance lives within a single context.</p><h4>… But There Can Be More Than One Context in an App</h4><p>If you think of contexts as scratch pads, you can immediately see why having multiple contexts could be a good thing.</p><ul><li>One context contains all the objects that are visible to the user in the main UI.</li><li>Another context could be used to parse and persist objects downloaded from a server. Since it’s not the UI context, the newly created objects would not appear immediately in the UI, and their retrieval would not block the UI. You could also discard that context entirely if the download or parsing failed.</li><li>Yet another context could be used to create a new object with the option to discard it if the creation process is canceled by the user.</li></ul><p>It is rare to develop a Core Data application with only one context.</p><h4>The Core Data Stack</h4><p>There are more pieces of the Core Data puzzle we have not mentioned so far: the persistent stores and persistent store coordinator. Together with the context and managed objects they form the Core Data stack.</p><p>The persistent stores are used to store the data. There can be more than one, even though on iOS you are likely to only have one. The persistent store coordinator is used to manage access to the persistent stores. It is also the holder of the one model used for all stores and manages all contexts connected to it. You can find more information on this topic in <a href="http://corporationunknown.com/presentations/CoreDataMultiStores.pdf">this presentation by fellow Pixel Paul Goracke</a>.</p><h4>What’s Important to Know About Contexts</h4><p>The Core Data concurrency model imposes that you specify the concurrency type of a context when you create it. As of iOS 9, there are two (non-deprecated) <a href="https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/index.html#//apple_ref/c/tdef/NSManagedObjectContextConcurrencyType">concurrency types</a>:</p><ul><li>The <em>NSMainQueueConcurrencyType</em> used by the main UI context in an application.</li><li>The <em>NSPrivateQueueConcurrencyType</em> used for a context running all operations on a private queue. Background contexts are typically initialized like this.</li></ul><p>When you are dealing with managed objects from the main UI context on the main thread, you can manipulate managed objects directly as you would any other object in an application.</p><p>In all other cases (accessing a managed object from the main context in another thread, making changes to a managed object belonging to a <em>PrivateQueue</em> context) the concurrency model imposes that you perform all operations on a managed object in its context’s queue using either of the two methods, <em>performBlock</em> or <em>performBlockAndWait</em>.</p><h4>A Word on Parent-Child Contexts</h4><p>Another important point that you need to get a good grip on is that contexts can be chained such that one is the child of another. If and when you do this, you have to realize that:</p><ol><li>Changes saved in a child context are pushed to the parent, not to the persistent store. The parent context behaves as the child’s persistent store.</li><li>Changes saved in a parent are not pushed down to the child.</li><li>Changes saved in a sibling are not pushed to other siblings.</li></ol><p>This means that changes only propagate one level up in a context hierarchy. If the context you are saving is several levels away from the persistent store, you will need to save each parent context in the hierarchy until you reach the context that saves to the persistent store to actually persist your changes.</p><blockquote>“There’s something very important I forgot to tell you.” — “What?” — “Don’t cross the streams.” — “Why?” — “It would be bad.” — Ghostbusters (1984)</blockquote><blockquote>“All that is left to us is Honor.” — Core Data famous last words</blockquote><p>Managed objects and contexts are like that; never pass a managed object directly from one context to another. It would be bad, as in, <em>“I’ve been chasing this random crash for two days”</em> bad.</p><p>And it is <em>very</em> easy to do. Fortunately the Core Data team at Apple added the launch argument for Xcode <strong>“com.apple.CoreData.ConcurrencyDebug”</strong> to iOS 8, making it easier for us to test against concurrency issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6eczxlH7E9C8nL7XzwmMA.png" /><figcaption>This should be your default for every single Core Data project you work on</figcaption></figure><p>Use it! Always! Make it part of your default Xcode template. It will save you hours of trouble down the line. It basically enforces a strict obedience of the Core Data concurrency model. With this option enabled you will see the following whenever you violate the concurrency rules:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*KUY0iq6fPodi7nn5swRj2w.png" /><figcaption>Core Data Multithreading model violation crash</figcaption></figure><h4>A Few Good Rules to Follow</h4><p><strong>Rule #1:</strong> No matter which thread you are on, you are guaranteed that the following two properties are safe to access on a managed object:</p><ul><li><em>objectID</em>, which gives you the unique ID of this managed object.</li><li><em>managedObjectContext,</em> which gives you the context this managed object lives on.</li></ul><p><strong><em>Accessing a managed object’s custom attributes, for reading or writing, must be done on the thread of the context managing that object. Failure to do so will violate the Core Data multi-threading contract. You will only have your honor left!</em></strong></p><p>Access to the managed object context also needs to be thread-safe. For instance in iOS 9 (and probably for prior versions as well), the method <em>hasChanges</em> on the context must be accessed on the context’s own thread.</p><p><strong>Rule #2: </strong>A<strong> </strong>managed object created on the main UI context can only be manipulated directly if it is on the main thread. Any attempt to manipulate this object on another thread may crash the application.</p><p><strong>Rule #3: </strong>A<strong> </strong>managed object belonging to a <em>PrivateQueue</em> context can only be manipulated on that context’s queue using either of the methods:</p><ul><li><a href="https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/index.html#//apple_ref/occ/instm/NSManagedObjectContext/performBlockAndWait:"><em>performBlockAndWait</em></a>, which will run whatever is within that block synchronously on the context’s queue.</li><li><a href="https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/index.html#//apple_ref/occ/instm/NSManagedObjectContext/performBlock:"><em>performBlock</em></a>, which will run whatever is within that block asynchronously on the context’s queue.</li></ul><p>One interesting fact: The method <em>performBlockAndWait</em> will likely run on the same thread it was called on, even if called on a <em>privateQueue</em> context.</p><p><strong>Rule #4:</strong> The main UI context can also use the two block methods to run code on its own queue (which is on the main thread). This is useful in cases where the main UI context must update some objects following an operation on another thread.</p><p>What these four rules mean in practice is that if you have a managed object and you don’t know whether the thread you are on is the one this object was created on, you can safely do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4093cfe9cda818f5c456516278665bf1/href">https://medium.com/media/4093cfe9cda818f5c456516278665bf1/href</a></iframe><p>You will read or hear that<em> just accessing custom properties is OK</em>. It may work in practice. But <em>the framework does not guarantee it and may crash</em>. When the Core Data concurrency debug launch option in Xcode<br>( - com.apple.CoreData.ConcurrencyDebug 1) is turned on, the app will crash if you access most properties on a managed object from a thread that is not the one the managed object was created on. That includes all your custom properties. Such access is regarded as a violation of the Core Data multithreading API contract. In addition to <em>objectID</em> and <em>managedObjectContext</em>, the following properties seem to be safely accessible from any thread:</p><ul><li><em>fault</em>,<em> faultingState</em>,<em> hasChanges</em>,<em> </em>and<em> entity</em>.</li></ul><p>The following properties are not thread-safe:</p><ul><li><em>custom properties</em>,<em> inserted, deleted</em>,<em> updated</em>,<em> changedValues</em>,<em> and hasFaultForRelationshipNamed</em>.</li></ul><p><strong>Rule #5:</strong> In 99.9 percent of the cases there is only one safe way to pass a managed object from one context to another: using its <em>objectID</em> and using the context confinement methods described above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5f67aa6360426ad732751824020deac/href">https://medium.com/media/a5f67aa6360426ad732751824020deac/href</a></iframe><p>The method <strong><em>objectWithID</em></strong><em> </em>used in this code is <em>fast but unsafe</em>. If the object no longer exists in the persistent store, accessing it will crash.</p><p>The method <strong><em>existingObjectWithID(: , error:)</em> </strong>is <em>slower but much safer</em>. It guarantees that the returned object exists in the store. That is why it is slower; it performs a round-trip to the store to retrieve the object. The many hard-to-debug crashes I have witnessed over the years have convinced me that the safety of this later method far outweighs the performance cost when dealing with multiple contexts. So I would encourage you to write this instead:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba82309fd309821b0b1f6bb57d96c451/href">https://medium.com/media/ba82309fd309821b0b1f6bb57d96c451/href</a></iframe><p>However, there are two cases where you can’t use the method above.</p><p>The first case is <strong>when your object does not have a permanent object ID</strong>. In this case you need to consider your Core Data stack configuration. In the snippet above:</p><ul><li>If the main context <em>is</em> the parent of the background context, retrieving the object by ID <em>will work</em>. The main context acts as the background context’s store. The background context therefore has access to that temporary ID.</li><li>If the main context <em>is not</em> the parent of the background context, retrieving the object by ID <em>will fail.</em> The temporary ID only exists in the main context and not in the store. The background context therefore has no access to that ID. In that case, you will need to <em>obtain a permanent object ID</em> for the objects in the main context using the API <em>obtainPermanentIDsForObjects(:error:)</em> <em>before</em> you can retrieve them in the background context.</li></ul><p>The second case is when contexts are connected to two different persistent store coordinators. This goes beyond this article. For more information on this topic, reference the <a href="https://www.objc.io/books/core-data/">upcoming objc.io book on Core Data</a>.</p><h4>Get Started With Core Data</h4><p>If this is all new to you, the <a href="https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Conceptual/CoreData/index.html#//apple_ref/doc/uid/TP40001075">Apple documentation</a> is a good place to start.</p><p>Paul Goracke has given several presentations on Core Data:</p><ul><li>Core Data Potpourri (<a href="https://vimeo.com/89370886">video</a> and <a href="http://xcoders.s3.amazonaws.com/2014-02-13%20Core%20Data%20Potpourri.pdf">pdf</a>).</li><li>Care and Feeding of Your Core Data Performance (<a href="http://corporationunknown.com/presentations/CoreDataPerformance.pdf">pdf</a>)</li><li>Multiple Presistent Stores in Code Data (<a href="http://corporationunknown.com/presentations/CoreDataMultiStores.pdf">pdf</a>)</li></ul><p>To set up your Core Data stack, the Apple sample Core Data application is not that great. I would refer you to “<a href="http://martiancraft.com/blog/2015/03/core-data-stack/">My Core Data Stack</a>” by Marcus Zarra, which provides a much better alternative to the default Apple code.</p><p>Finally, there is a <a href="https://www.objc.io/books/core-data/">book coming out really soon</a> written by Florian Kugler and Daniel Eggert from objc.io which is very current and extensively covers some advanced Core Data topics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f095ecb1882" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bpxl-craft/some-lessons-learned-on-core-data-5f095ecb1882">Some Lessons Learned on Core Data</a> was originally published in <a href="https://medium.com/bpxl-craft">BPXL Craft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing Inspirato’s Search Tool]]></title>
            <link>https://medium.com/bpxl-craft/developing-a-new-way-to-search-cf1a46d382df?source=rss-7c87a5c46111------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf1a46d382df</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Michael Gachet]]></dc:creator>
            <pubDate>Fri, 23 Oct 2015 20:13:28 GMT</pubDate>
            <atom:updated>2015-10-26T19:11:05.857Z</atom:updated>
            <content:encoded><![CDATA[<p>During the discovery process for the project, the Inspirato team kept emphasizing how their members were booking vacation mostly over the phone using broad statements about the type of vacation experience they were looking for. It became clear that we needed to offer something more than your standard search paradigm.</p><p>Natural Language Search (NLS) was proposed to offer something very different from traditional search and yet very similar to the way Inspirato members were thinking about and booking their vacations.</p><p>Designed and developed by Black Pixel for Inspirato, Natural Language Search allows users to interactively create sentences about the kind of travel experience they are looking for.</p><p>In a world where the typical search is a text field associated with a bunch of checkboxes, NLS stands out. You can formulate a search as you would naturally talk. It just makes sense. It just works. By tapping and scrolling you can create rich natural sentences.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_dlGinN8wxI%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_dlGinN8wxI%26feature%3Dyoutu.be&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_dlGinN8wxI%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4302cfe25e2f6a41513b0cdf17177862/href">https://medium.com/media/4302cfe25e2f6a41513b0cdf17177862/href</a></iframe><p>This post will take you behind the scenes for a deeper look at the way NLS works.</p><h4>Some History</h4><p>When you see a finished application it is sometimes difficult to imagine the amount of work that went into the implementation of certain features. Some may seem daunting, others dead simple. The truth is that no nice, polished feature is ever the result of just a few hours of work. Most polished features, even if they look simple, are often the end result of hours of hard work and many iterations. NLS is one such feature. It was not created in a few days. In fact it took the better part of three months to come to the level of polish you see today.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fsh7K9Zn2aco%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dsh7K9Zn2aco%26feature%3Dyoutu.be&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fsh7K9Zn2aco%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a10f29882b910da0d317ec8db2275457/href">https://medium.com/media/a10f29882b910da0d317ec8db2275457/href</a></iframe><p>Of course we had a visual prototype working within a few days, but as the most experienced software engineers know, there is a wide gap between a working visual prototype and a fully functioning, fully refined feature.</p><p>The visual design started on the iPad knowing that we would need to implement NLS on the iPhone at a later stage. At the time the iPhone 6 and iPhone 6 Plus had not been introduced yet.</p><h4>What’s an NLS Sentence?</h4><p>Before we look at the data model and visual implementation, let’s start with a short explanation of NLS sentences.</p><p>When users interact with NLS they are usually awed by the nice visual interaction and animation. It feels natural and users typically find it delightful. The search sentence sounds so natural they don’t think about it. Let’s have a closer look at how the search sentence is built up.</p><p>It always starts the same way with, “I want to …” This group is then followed by an action verb and options for a location and a time. Changing the action verb impacts what should come next, such as the prepositions:</p><ul><li>Vacation on the beach anytime.</li><li>Vacation in a city anytime.</li><li>Vacation anywhere (no preposition) anytime.</li><li>Jaunt to the mountains.</li><li>Daydream in the countryside.</li></ul><p>Changing the action also affects the possible content of the sentence:</p><ul><li>The list of locations for a “Jaunt” is changing every week based on current “Jaunt” offerings.</li><li>When you daydream, you don’t specify a time.</li><li>When the selected location is a geographic region, the sentence also displays the associated destinations for that region.</li></ul><p>The list of locations shown to the user offers a variety of choices:</p><ul><li>Anywhere, which gives access to all destinations.</li><li>A region (the Bahamas, the South), which gives access to specific destinations.</li><li>A vacation style (city, mountains, beach).</li><li>A typed location, which is a standard text search.</li></ul><p>The way these words relate to actual residences or destinations can be rather complex.</p><p>The sentence itself allows you to look for residences to plan your next vacation so it has to translate into a list of residences or destinations.</p><h4>Diving into the NLS Architecture</h4><p><strong>Model and Controllers and Views</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cB7pgncdeGuX6jrnCh0ZoA.png" /><figcaption>The overall NLS architecture showing the main components and their relationships. Some elements are omitted for the sake of clarity.</figcaption></figure><p>The NLS architecture relies on two major components:</p><ul><li>The Sentence Controller, which is responsible for ensuring the sentence is always syntactically and grammatically correct no matter what words are selected.</li><li>The Sentence View Controller, which is responsible for the display and layout of the sentence, as well as handling all user interactions.</li></ul><p>The delegation relation that exists between both ensures that all changes made to the Sentence Controller (like when a user selects a previous search sentence in the history) are properly reflected visually.</p><p><strong>The Sentence Controller</strong></p><p>At the heart of sentence management is the sentence controller. This controller:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1rdYMSltYIMrRWkxwlAIww.png" /><figcaption>Sentence Controller: the beating heart of NLS</figcaption></figure><ul><li>Manages the prepositions of each collection of words to ensure a consistent grammatical sentence.</li><li>Enforces the rules about sentence creation such as “daydream does not allow time selection.”</li><li>Updates the list of words (action, location, sub location, and time) based on the currently selected words.</li><li>Updates the sentence model with the current word selection.</li><li>Initializes the current selection based on a given sentence or initial state.</li><li>Communicates changes made to the sentence back to the view.</li></ul><p>The list of available residences and destinations, which is regularly retrieved from the Inspirato server, determines which locations can be shown to the user.</p><p>The sentence can be changed in several ways:</p><ul><li>A user can edit the sentence visually.</li><li>A user can pick a previous sentence from history of past searches.</li><li>A user can receive a push notification with a specific sentence, such as for new “Jaunt” offerings.</li><li>A residence or destination may be removed from the Inspirato offering temporarily or permanently.</li></ul><p>All of these cases have to be handled gracefully by the sentence controller to ensure the sentence is always correct and all residences or destinations shown are current.</p><p><strong>Core Data</strong></p><p>Core Data is used to model all the instances making up this model. All location words (region, vacation style, destinations, residences) are related to actual destinations or residences the user can see. The relationship model of core data makes retrieving this information very easy.</p><p>One complexity of the model is figuring out which words to display. For example, when the user selects the action “Jaunt,” we need to show destinations that match several criteria:</p><ol><li>The destinations shown need to contain residences that are “Jaunt” residences,</li><li>But should not show residences that are temporarily off the market (for maintenance, for example),</li><li>And should correspond to the selected location word.</li></ol><p>This sometimes results in rather complex fetch requests made of up to three levels of subquery.</p><p><strong>The Sentence View Controller</strong></p><p>Without the sentence view controller there would be no NLS as we know it. All the work done to layout the NLS sentence and manage user interactions goes through the sentence view controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mDR3-WBgwiPxxs6zfljZQ.png" /><figcaption>The visual brains of NLS: the sentence view controller</figcaption></figure><p>Whenever a list expands or collapses it communicates its state to the sentence view controller, which can:</p><ul><li>Relay the information to the sentence controller (to change the sentence).</li><li>Layout the views dynamically.</li></ul><h4>A Deeper Look at the Visual Design Implementation</h4><p>From the beginning, Inspirato was going to be both an iPad and iPhone application. All decisions made while designing NLS for the iPad were done so knowing that the iPhone would come next.</p><p><strong>The Root of NLS Design: The iPad</strong></p><p>There are several moving pieces in the iPad visuals. Let’s start with the default NLS sentence which greets the user the first time she uses the application. When she taps on the “anywhere” word to choose a new destination the following happens simultaneously:</p><ol><li>The list of locations expands vertically with all destinations moving into place.</li><li>The list of locations expands horizontally so as to accommodate all destinations using a single line layout for each.</li><li>The horizontal expansion of the list pushes the rest of the sentence to the side or another line.</li></ol><p>The overall animation is very smooth with everything moving into place nicely and naturally. This is best illustrated with a video.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2Dga6POZJwM%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2Dga6POZJwM%26feature%3Dyoutu.be&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2Dga6POZJwM%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/108325b728a8006bde1e90ce56ff3715/href">https://medium.com/media/108325b728a8006bde1e90ce56ff3715/href</a></iframe><p><strong>The Sentence Layout</strong></p><p>Laying out the sentence’s words is the easiest part. The sentence is composed of up to 11 different views from the opening statement to the period at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sYZiIinfba0V6jE3JVxeHQ.png" /><figcaption>Some NLS sentence views exposed</figcaption></figure><p>The views are not laid out individually; they are grouped logically to ensure a pleasant and natural layout. For example, the location word can display a region, in which case a disclosure indicator will be displayed. These two views (disclosure indicator and destination) are grouped together and laid out as one. Similarly, the period is attached to whatever word precedes it so it doesn’t end up alone on a line.</p><p>The algorithm to layout the views is relatively straightforward once you know the width of all the views you want to layout. The algorithm takes the array of widths to layout along with the total available width and distributes the views on different lines. The constraints of the different views are then updated to position the views horizontally and vertically.</p><p><strong>The Lists of Words</strong></p><p>The lists of words are central to the sentence creation process. Using these lists, the user can select different words to make up the complete search sentence.</p><p>Each list uses a <em>UITableView</em> which will:</p><ul><li>Change its width according to the current selection, or, when a list is expanded, accommodate the widest entry in that list. Each row in the list has the same row height.</li><li>Change its height dynamically from a single row height to the full height of the iPad screen when the list expands to reveal its words.</li><li>Animate its cells to their final position during an expansion or a collapse by applying a 2D transform to each cell.</li></ul><p>In order to make this work smoothly on the iPad we use several tricks:</p><ul><li>We pre-compute the maximum width of all cells in their non-selected state using a template cell set up with autolayout. This ensures a very fast computation of the table view width when it expands to reveal its content.</li><li>A width constraint is set on the table view and updated to dynamically change its width. The sentence view controller can read this updated width for the layout computation.</li></ul><p>The principles are easy enough to understand. The devil is really in the details:</p><ul><li>The sequence of animations is important and often non-commutative, especially with auto layout: performing update A before update B does not yield the same results as proceeding the other way around.</li><li>The timing of animations is tricky: you need to always end up in a consistent state at the end of each animation, both for the list and the sentence.</li></ul><p>Let’s look at the details of what happens during the expansion of a list.</p><p><strong>Revealing a List’s Content</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFcKVW3Iz8ac%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFcKVW3Iz8ac%26feature%3Dyoutu.be&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFcKVW3Iz8ac%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dac1716b84ea806f5b4f7a9be06d5bb/href">https://medium.com/media/2dac1716b84ea806f5b4f7a9be06d5bb/href</a></iframe><p>The video above shows a slow motion video of a list expansion. It was created by slowing down the animations in code. The picture below describes the various steps of this animation from start to finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s0vu3QapabXPGQzmNn5EXw.png" /><figcaption>From a single word to a list of words: all the steps of an NLS list expansion</figcaption></figure><p>To synchronize those steps we make use of the dispatch_group_enter dispatch_group_leave dispatch_group_notify methods. This ensures that we get properly notified once all animations have completed without imposing an a priori time limit. During this completion phase we perform several tasks such as re-enabling scrolling for the table view and telling our delegate that the expansion is completed.</p><p>Getting there was not straightforward. Far from it. It took a lot of experimentation, a lot of broken animations, and a lot of very intensive, relentless, ruthless testing. Working with a great QA team helped tremendously. NLS would not have reached the level it is at right now without this extremely tight and constant back-and-forth between engineering and QA. And quite honestly sometimes I got scared of submitting changes knowing that QA would break the whole thing apart without mercy. But this is what it takes to make great software.</p><p><strong>What About the iPhone?</strong></p><p>Implementing NLS for the iPhone was relatively straightforward with minimal changes to the original algorithm and design.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fg0prcjQQ624%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dg0prcjQQ624%26feature%3Dyoutu.be&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fg0prcjQQ624%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d96c8088cf3a135f48e15f466c5fa820/href">https://medium.com/media/d96c8088cf3a135f48e15f466c5fa820/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5OmcMAL98Xo%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5OmcMAL98Xo%26feature%3Dyoutu.be&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5OmcMAL98Xo%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a439a8473787d98dec550f253557b6e/href">https://medium.com/media/6a439a8473787d98dec550f253557b6e/href</a></iframe><p>If you look closely at the iPhone design you will notice:</p><ul><li>Each of the 11 views used to represent the sentence lives on a different line. This was achieved by telling the layout algorithm that each view had the width at the iPhone screen (minus some margins). Without any changes, the algorithm positioned each view on different lines.</li><li>Each list has rows of varying height.</li></ul><p>So in essence the design went from a “varying width/fixed table row height” on the iPad to a “fixed width/variable table row height” on the iPhone.</p><p>On iPhone, instead of pre-computing the width of all cells, we pre-computed their height for the non-selected state using the same template cell and autolayout. This ensured we could very easily provide each row height upon the list expansion.</p><p>Apart from these changes the rest of the code remains almost identical for the sentence layout and the list animation.</p><h4>Pushing the Limits</h4><p>The design team at Black Pixel loves to push the limits of what can be done to delight our users with great experiences. When I first saw the design for NLS, I immediately noticed its appeal. I could visualize the animations and interactions. I was loving it. And as a developer, I was terrified because I knew it was very different from any interactions I had ever seen. I had just joined Black Pixel and, quite frankly, I did not know whether I would be up to the challenge. And then I was asked to work on it … and the adventure started. The fear is <em>mostly</em> gone.</p><p>The NLS feature you see today is the result of an intense and continuous collaboration with both the design and QA teams. I am grateful to both teams for pushing my limits and allowing me to grow and perfect my craft. Being part of this project and having the opportunity to work as part of Black Pixel’s great integrated multidisciplinary team has been a real privilege.</p><p>If you want to see the app in action you can <a href="https://itunes.apple.com/us/app/inspirato/id970207197?mt=8">download the Inspirato app</a> from the App Store.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf1a46d382df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bpxl-craft/developing-a-new-way-to-search-cf1a46d382df">Developing Inspirato’s Search Tool</a> was originally published in <a href="https://medium.com/bpxl-craft">BPXL Craft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Objective-C to Swift: A Journey]]></title>
            <link>https://medium.com/bpxl-craft/from-objective-c-to-swift-a-journey-c8732c3a3c6?source=rss-7c87a5c46111------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8732c3a3c6</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Michael Gachet]]></dc:creator>
            <pubDate>Fri, 12 Jun 2015 16:53:33 GMT</pubDate>
            <atom:updated>2015-06-12T16:53:33.582Z</atom:updated>
            <content:encoded><![CDATA[<p>I am French. English is not my first language. I apologize in advance for any gallicism which may sneak its way into this article. But first let me explain what a gallicism is: It’s a typical French idiom or construct applied to a foreign language. It can be an obvious and clear intention of the speaker, such as when Neo says, “Dejà vu,” when he sees that black cat for a second time. But when you are French this is usually what your English teacher writes in red on your essays when you’ve just translated, word for word, a typical French idiom into English. Something like, “It’s raining ropes,” instead of, “It’s raining cats and dogs.” I may even be writing some at the moment… Just let me know if you see one.</p><p>When I was 13 and learning English, my teacher told me, “A language is all about grammar and vocabulary,” and sent me home with pages of vocabulary to memorize. Since then I’ve learned that a language is a lot more than grammatical rules and vocabulary. Any language has a symbiotic relationship with its culture. Culture and language evolve hand-in-hand, and it can be difficult to know how they are influencing each other. With English, a very dynamic language, you can witness the emergence of new idiomatic expressions or words. In turn, these shape the way we express ourselves, our thoughts, and our reasoning. New words are like new conceptual abstractions which can lead us to think and act differently. George Orwell illustrated this very well in “1984” with Newspeak: a language devoid of nuances, meant to limit the way people think. But you don’t need a dystopian future to understand this; just try to express yourself in a foreign language you barely know and tell me how you feel. I usually feel pretty stupid.</p><h3>A Learning Opportunity</h3><p>What does that have to do with Swift? Let me get to this.</p><p>I, along with some of my colleagues at <a href="http://blackpixel.com/">Black Pixel</a>, have just completed a massive project written entirely in Swift. We developed a uniquely designed universal app for the iPad and iPhone. It took a substantial team of engineers, designers, project managers, and testers the better part of eight months to complete. Until Apple released Swift 1.2 we struggled with compilation times of several minutes every time we made the smallest change.</p><p>The decision to move to Swift was very daring for such a project and a great opportunity to learn.</p><p>We started by reading The Swift Programming Language, an overview that includes a mix of simple examples and grammatical rules. After overcoming my habit of typing semicolons, I felt comfortable writing code in Swift, but, dare I say, my level of expression in that code was not very fluent. The code I wrote worked but felt clunky and ugly, full of `if` statements and forced unwrapping of optionals.</p><p>That code was written in Swift, but it was full of Objective-C idioms. While it worked, it could have been written better. And so my journey began to try to learn more about the cultural fabric of Swift and become a more fluent practitioner of the language.</p><p>I was helped along the way by some great engineers. Kevin Ballard and Vic Smith had experience with functional programming, and their knowledge and mastery of the culture behind Swift proved invaluable.</p><p>I do not have a preference for one language over the other, and I am <em>not</em> an expert in programming languages. My goal is to merely illustrate a few of the main discoveries I made regarding Swift over the past eight months. For each example I will show a piece of code very similar to what I was writing at the start of the project, these so-called Objective-C idioms. I will also have a functionally identical piece of code written in the spirit of Swift. All code can be directly pasted into Playground to see it in action.</p><h3>Optionals and Their ?, !, and ??</h3><p>Simply put optionals are data containers which may or may not contain data. They are great for safely and clearly expressing data which may not exist, such as the `delegate` of a view controller or any other piece of data. In Swift, if an optional contains no data it is `nil`, otherwise it is not.</p><p>Coming from Objective-C, optionals are a weird beast: We are indeed used to dealing with `nil` values either implicitly or explicitly but as values nonetheless. So a typical way to deal with optionals within an Objective-C mindset is quite different from the intended idiomatic use. Here are a few examples:</p><h4>Doing something with an optional when it’s not nil</h4><p>Let’s say you want to print the content of your optional only if it’s not nil. How would you go about it?</p><pre>// Objective-C idiom: you check that it’s not nil and you unwrap it<br>let anOptional: String? = “bonjour”<br>if anOptional != nil {<br>   println(“We say \(anOptional!)”) // Will print “We say bonjour”<br>}</pre><pre>// Swift idiom: use optional binding<br>if let anOptional = anOptional {<br>   println(“We say \(anOptional)”) // Will print “We say bonjour”<br>}</pre><p>To me the main hurdle was feeling comfortable allocating a new variable with which to bind my optional. After years of programming, I’d developed a reflex against allocating variables when I don’t feel it’s needed. But it’s fine now. I’m cured!</p><h4>Logical statements involving several optionals</h4><p>Let’s consider two `String?` constants: `bonjour` and `mademoiselle`. We want to write:</p><ul><li>“Bonjour Mademoiselle” if both are not empty.</li><li>“Bonjour” if `mademoiselle` is empty.</li><li>“Comment allez-vous Mademoiselle?” if `bonjour` is empty.</li><li>“Mmmm…” if both are empty.</li></ul><pre>let bonjour: String? = “Bonjour”<br>let mademoiselle: String? = “Mademoiselle”</pre><pre>// Objective-C idiom: using if…else statements checking for nil and force-unwrapping optionals</pre><pre>if bonjour != nil &amp;&amp; mademoiselle != nil {<br>   println(“\(bonjour!) \(mademoiselle!)”)<br>} else if bonjour != nil &amp;&amp; mademoiselle == nil {<br>   println(bonjour!)<br>} else if bonjour == nil &amp;&amp; mademoiselle != nil {<br>   println(“Comment allez-vous \(mademoiselle!)?”)<br>} else {<br>   println(“Mmmm…”)<br>}</pre><p>There would be at least two ways to deal with this using a more idiomatic construct in Swift:</p><ol><li>Using optional binding on multiple variables and an `if…else` statement.</li><li>Using a `switch` statement on the tuple `(bonjour, mademoiselle)`.</li></ol><p>I will focus on the `switch` statement because this was the hardest one for me to internalize. Indeed I have been programming using C-based languages for so long that in my mind a `switch` was for `enum` or `integer` types only. This is not the case in Swift where `switch` statements can be used as very powerful filters on any type of data.</p><p>Here is an example of using a `switch` statement on the tuple `(bonjour, mademoiselle)`:</p><pre>switch (bonjour, mademoiselle) {<br>   case let (.Some(string1), .Some(string2)): // If both optionals are non nil: we unwrap their values into local constants `string1` and `string2`<br>      println(“\(string1) \(string2)”)</pre><pre>   case let (.Some(string1), _): // mademoiselle is nil, bonjour is not: we unwrap bonjour’s value into local constant string1<br>      println(“\(string1)”)</pre><pre>   case let (_, .Some(string2)): // bonjour is nil, mademoiselle is not: we unwrap mademoiselle’s value into local constant string2<br>      println(“Comment allez-vous \(string2)?”)</pre><pre>   case (_, _): // Both are nil<br>      println(“Mmmm…”)<br>}</pre><p>Nowadays I use this type of logical construct almost everywhere instead of the more complex `if…else` because:</p><ol><li>It’s clear.</li><li>The Swift compiler will complain if you have not covered all cases.</li></ol><h4>Comparing an optional with some other value</h4><p>This took me a while to wrap my head around. I used the Objective-C idiom for a while before finally dropping it entirely. Consider the following examples:</p><pre>// Objective-C idiom:<br>let anOptional: String? = “bonjour”</pre><pre>if anOptional != nil &amp;&amp; anOptional! == “bonjour” {<br>   println(“We say bonjour”)<br>}</pre><pre>// Swift idiom: turn your value into an Optional<br>// Note this is not strictly required. For most types Swift will do this for you</pre><pre>if anOptional == .Some(“bonjour”) {<br>   println(“We say bonjour”)<br>}</pre><p>A practical application of this would be when you are overriding the function `traitCollectionDidChange` method on `UIViewController` because you are dealing with `SizeClass`:</p><pre>override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {</pre><pre>   super.traitCollectionDidChange(previousTraitCollection)</pre><pre>   if previousTraitCollection.userInterfaceIdiom == .Some(self.traitCollection.userInterfaceIdiom) {<br>      return<br>   }<br>   // Do something here<br>}</pre><h4>Assigning an optional value to another variable</h4><p>Sometimes you need to assign an optional value to another variable, for instance assigning an optional `String` to the `text` property of a `UILabel`:</p><pre>let label = UILabel()<br>var string : String?</pre><pre>// Objective-C idiom: check whether the string is nil and use an if…else statement</pre><pre>func updateLabelWithObjectiveCIdiom(label: UILabel, withString string: String?) {<br>   if string != nil {<br>      label.text = string!<br>   } else {<br>      label.text = “This is an empty string”<br>   }<br>}</pre><pre>// Swift idiom: using the ?? operator on the optional<br>func updateLabelWithSwiftIdiom(label: UILabel, withString string: String?) {<br>   label.text = string ?? “This is an empty string”<br>}</pre><pre>updateLabelWithObjectiveCIdiom(label, withString: nil)<br>label.text // Contains “This is an empty string”</pre><pre>updateLabelWithSwiftIdiom(label, withString: nil)<br>label.text // Contains “This is an empty string”</pre><pre>updateLabelWithObjectiveCIdiom(label, withString: “This is NOT an empty string”)<br>label.text // Contains “This is NOT an empty string”</pre><pre>updateLabelWithSwiftIdiom(label, withString: “This is NOT an empty string”)<br>label.text // Contains “This is NOT an empty string”</pre><h4>Passing an optional to a function which does not take an optional as parameter</h4><p>Another interesting thing to know is how to pass an optional to a method which does not take an optional as parameter. Here is a mockup `UIViewController` subclass with a `UILabel` meant to represent a birthday date. This controller has:</p><ol><li>A method `updateBirthdayWithDate(date: NSDate?)`.</li><li>A lazily initialized `NSDateFormatter` that we will use to convert the `NSDate?` into a `String`.</li></ol><p>The method `stringFromDate(date: NSDate)` of `NSDateFormatter` takes an `NSDate` parameter. How would you go about updating your label with the `NSDate?`:</p><pre>class OptionalsViewController : UIViewController {<br>   let birthdayLabel : UILabel? = UILabel()<br>   lazy var dateFormatter : NSDateFormatter = {<br>      let dateFormatter = NSDateFormatter()<br>      dateFormatter.dateStyle = .LongStyle<br>      dateFormatter.timeStyle = .NoStyle<br>      return dateFormatter<br>   }()</pre><pre>   func updateBirthdayWithDate(date: NSDate?) {<br>      // NSDateFormatter.stringFromDate takes an NSDate as parameter, not an NSDate?</pre><pre>      // The Objective-C mindset: making sure date is not nil and force-unwrap<br>      if date != nil {<br>         self.birthdayLabel?.text =       self.dateFormatter.stringFromDate(date!)<br>      }</pre><pre>      // Swift idiom: use the map function on the optional<br>      self.birthdayLabel?.text = date.map({          self.dateFormatter.stringFromDate($0) }) ?? “”<br>      }<br>   }<br>}</pre><p>Using Playground you can see this code in action:</p><pre>let controller = OptionalsViewController()<br>controller.updateBirthdayWithDate(NSDate())<br>controller.birthdayLabel?.text // Will print whatever date today is</pre><pre>controller.updateBirthdayWithDate(nil)<br>controller.birthdayLabel?.text // Will print “”</pre><p>The `map` function can be called on any optional to unwrap it and call a method on the unwrapped value if it exists. If the optional is nil, the `map` function will return `nil`, which is very convenient if you remember it exists.</p><h3>Operating on Arrays</h3><p>Swift’s built-in `Array` type is very powerful once you get to know it. It is tempting to use NSArray or NSMutableArray for some operations until you realize you often don’t need to. Here are a few examples, again comparing my initial use of Objective-C idioms with Swift ones.</p><h4>The map function</h4><p>Let’s say you want to pin all edges of a `view` to a `parentView`.</p><pre>// The idiomatic Objective-C way could be to write this:<br>parentView.addConstraints([NSLayoutConstraint(item: view, attribute: .Left, relatedBy: .Equal, toItem: parentView, attribute: .Left, multiplier: 1, constant: 0),<br>NSLayoutConstraint(item: view, attribute: .Right, relatedBy: .Equal, toItem: parentView, attribute: .Right, multiplier: 1, constant: 0),<br>NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal, toItem: parentView, attribute: .Top, multiplier: 1, constant: 0),<br>NSLayoutConstraint(item: view, attribute: .Bottom, relatedBy: .Equal, toItem: parentView, attribute: .Bottom, multiplier: 1, constant: 0)])</pre><pre>// Using an Array and the map function, the Swift version would look like this:<br>parentView.addConstraints([NSLayoutAttribute.Left, .Bottom, .Right, .Top].map({ edge in<br>   NSLayoutConstraint(item: view, attribute: edge, relatedBy: .Equal, toItem: parentView, attribute: edge, multiplier: 1, constant: 0)}))</pre><p>This creates an array of `NSLayoutAttribute`: `[NSLayoutAttribute.Left, .Bottom, .Right, .Top]` for all four edges.</p><p>Then the `map` function will apply the code in the provided closure to each element in that array.</p><h4>Mutable arrays</h4><p>Consider the following scenario: You are modeling a company that contains departments. Each department has employees, and you need to build an array containing all employees.</p><p>A natural way to do this in Objective-C is to use an `NSMutableArray` to store all employees, iterate over the departments, and call `addObjectsFromArray` to add the department’s employees to the store employees.</p><p>It would look something like this:</p><pre>class Company {<br>   var departments: [Department]?</pre><pre>   // With the Objective-C mindset you would probably write something like this:<br>   func allEmployeesObjectiveC() -&gt; NSArray {<br>      var employees = NSMutableArray()<br>      if self.departments != nil {<br>         for department in self.departments! {<br>            if department.employees != nil {<br>               employees.addObjectsFromArray(department.employees!)<br>            }<br>         }<br>       }<br>      return employees<br>   }</pre><pre>   // Once familiar with Swift idioms your code would probably look like that:<br>   func allEmployeesSwift() -&gt; [String] {<br>      var employees : [String] = Array()</pre><pre>      for department in self.departments ?? [] {<br>         employees += department.employees ?? []<br>      }<br>      return employees<br>   }<br>}</pre><pre>class Department {<br>   var employees: [String]?<br>}</pre><p>In Playground you could test to see that you get identical results by writing this:</p><pre>let company = Company()<br>let romanticDepartment = Department()</pre><pre>romanticDepartment.employees = [“Sally”, “Harry”]</pre><pre>let wizzardDepartment = Department()<br>wizzardDepartment.employees = [“Harry”, “Hermione”, “Ron”]</pre><pre>let dumbDepartment = Department()<br>dumbDepartment.employees = [“Dan”, “Forrest”, “Buba”]</pre><pre>company.departments = [romanticDepartment, wizzardDepartment, dumbDepartment]</pre><pre>company.allEmployeesSwift()<br>// will print [“Sally”, “Harry”, “Harry”, “Hermione”, “Ron”, “Dan”, “Forrest”, “Buba”]</pre><pre>company.allEmployeesObjectiveC()<br>// will print [“Sally”, “Harry”, “Harry”, “Hermione”, “Ron”, “Dan”, “Forrest”, “Buba”]</pre><h4>Sorting arrays</h4><p>Building on the previous example, if you want to sort the resulting array of employees you could write something like this:</p><p>Objective-C mindset: the `allEmployeesObjectiveC()` returns an `NSArray` which contains the employees names. Items in this array are of type `AnyObject` and will need to be cast to `String` for comparison.</p><pre>let employeesObjC = company.allEmployeesObjectiveC().sortedArrayUsingComparator {   (name1, name2) -&gt; NSComparisonResult in</pre><pre>   // Cast `name1` and `name2` to `String`:<br>   if let name1 = name1 as? String, name2 = name2 as? String { // This is pretty Swift-like<br>      return name1.caseInsensitiveCompare(name2)<br>   }<br>   return .OrderedSame<br>}</pre><pre>employeesObjC<br>// Will print [“Buba”, “Dan”, “Forrest”, “Harry”, “Harry”, “Hermione”, “Ron”, “Sally”]</pre><p>Swift mindset: use the `sorted` function on the array of employees. Since it’s an array of `String` we can directly compare the strings together:</p><pre>let employeesSwift = company.allEmployeesSwift().sorted{ $0.caseInsensitiveCompare($1) == .OrderedAscending }</pre><pre>employeesSwift</pre><pre>// Will print [“Buba”, “Dan”, “Forrest”, “Harry”, “Harry”, “Hermione”, “Ron”, “Sally”]</pre><h4>Dealing with enums</h4><p>Swift enums are first class citizens, not just a collection of numbers used to organize options. I must admit that I still struggle to find ways to fully leverage the power of Swift enums. Still, there are a few things I learned along the way.</p><h4>The Printable or DebugPrintable protocols are your friends</h4><p>`Printable` or `DebugPrintable` are two protocols you should implement for your `enum` if you want to see something other than `(Enum Value)` when you attempt to debug an enum value in lldb.</p><p>Here is an example:</p><pre>enum Position: Int, Printable {<br>   case Up = 0<br>   case Down<br>   case Left<br>   case Right</pre><pre>static let allValues : [Position] = [.Up, .Down, .Left, .Right]</pre><pre>// This is the whole implementation of the `Printable` protocol<br>   var description: String {<br>      get {<br>         switch self {<br>            case .Up:<br>            return “Up”</pre><pre>case .Down:<br>            return “Down”</pre><pre>case .Left:<br>            return “Left”</pre><pre>case .Right:<br>            return “Right”<br>         }<br>      }<br>   }</pre><h4>Enums can be any type, not just Int</h4><p>Below is an enum that lists some of the existing models of iOS hardware. In this case, the benefits of using an enum with a `rawValue` of type `String` is obvious, as are the benefits of having methods on the enum.</p><pre>enum DeviceModel : String, Printable {<br>   case iPhone5_3 = “iPhone5,3” // (model A1456, A1532 | GSM)<br>   case iPhone5_4 = “iPhone5,4” // (model A1507, A1516, A1526 (China), A1529 | Global)<br>   case iPhone6_1 = “iPhone6,1” // (model A1433, A1533 | GSM)<br>   case iPhone6_2 = “iPhone6,2” // (model A1457, A1518, A1528 (China), A1530 | Global)<br>   case iPhone7_1 = “iPhone7,1” // All iPhone 6 Plus’s<br>   case iPhone7_2 = “iPhone7,2” // All iPhone 6&#39;s<br>   case Unknown = “Unknown</pre><pre>   var description: String {<br>      return rawValue<br>   }</pre><pre>   var name: String {<br>      switch self {<br>         case .iPhone5_3: return “iPhone 5c”<br>         case .iPhone5_4: return “iPhone 5c”<br>         case .iPhone6_1: return “iPhone 5s”<br>         case .iPhone6_2: return “iPhone 5s”<br>         case .iPhone7_1: return “iPhone 6 Plus”<br>         case .iPhone7_2: return “iPhone 6”<br>         case .Unknown: return “(unknown)”<br>      }<br>    }</pre><pre>   var isIphone6Plus: Bool {<br>      return self == .iPhone7_1<br>   }</pre><pre>   var isIphone6: Bool {<br>      return self == .iPhone7_2<br>   }</pre><pre>   var isIphone5: Bool {<br>      let devices: [DeviceModel] = [.iPhone5_1, .iPhone5_2, .iPhone5_3, .iPhone5_4, .iPhone6_1, .iPhone6_2]<br>      return contains(devices, self)<br>   }<br>}</pre><p>You could easily use such an enum in a `UIDevice` extension:</p><pre>extension UIDevice {<br>   var modelString: String {<br>      var systemInfo = utsname()<br>      uname(&amp;systemInfo)<br>      let identifier = withUnsafeMutablePointer(&amp;systemInfo.machine) {   ptr in String.fromCString(UnsafePointer&lt;CChar&gt;(ptr))}<br>      return identifier ?? “”<br>   }</pre><pre>   var modelName: String {<br>      let name = self.modelString<br>      return DeviceModel(rawValue: name)?.name ?? name<br>   }</pre><pre>   var model: DeviceModel {<br>      return DeviceModel(rawValue: self.modelString) ?? .Unknown<br>   }<br>}</pre><p>The added benefit of this is that in your code you could then use a robust `switch` statement on `UIDevice.currentDevice.model`. The mapping is defined once in the `enum` and you no longer need to perform string comparisons which are usually error-prone.</p><h4>Looping over all cases in an enum</h4><p>There is no built-in `allValues` method for enums, so if you ever want to loop over all the cases in your enum you have to add a method for this. For instance, we could add the following constant to the `Position` enum:</p><pre>enum Position: Int, Printable {<br>   case Up = 0<br>   case Down<br>   case Left<br>   case Right</pre><pre>   static let allValues : [Position] = [.Up, .Down, .Left, .Right]</pre><pre>   // This is the whole implementation of the `Printable` protocol<br>   var description: String {<br>      get {<br>         switch self {<br>            case .Up:<br>            return “Up”</pre><pre>            case .Down:<br>            return “Down”</pre><pre>            case .Left:<br>            return “Left”</pre><pre>            case .Right:<br>            return “Right”<br>         }<br>      }<br>   }<br>}</pre><p>With this in place you can very easily iterate over all cases:</p><pre>for position in Position.allValues {<br>   println(position)<br>}</pre><pre>// This will print: Up, Down, Left, Right</pre><pre>// Had you not implemented the Printable protocol, you would see: (Enum Value) (Enum Value) (Enum Value) (Enum Value).</pre><h3>Clearing Hurdles</h3><p>I realize that some of the examples presented in this article may be simplistic or downright artificial. However, they illustrate some of the most difficult mental challenges that I needed to overcome when transitioning from Objective-C to Swift.</p><p>The challenge with learning the Swift language is not the new syntax. That’s the easy part. The real hurdles are altering the way we think in order to become fluent speakers of that language, understanding where the language is coming from, mastering its idioms, and ultimately becoming indistinguishable from native speakers. I know I’m not there yet. Are you?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8732c3a3c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bpxl-craft/from-objective-c-to-swift-a-journey-c8732c3a3c6">From Objective-C to Swift: A Journey</a> was originally published in <a href="https://medium.com/bpxl-craft">BPXL Craft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>