<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>Cocoa Is My Girlfriend</title>
	
	<link>http://www.cimgf.com</link>
	<description>Taglines are for Windows programmers</description>
	<lastBuildDate>Wed, 16 May 2012 13:14:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/CocoaIsMyGirlfriend" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="cocoaismygirlfriend" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Unit Testing with Core Data</title>
		<link>http://www.cimgf.com/2012/05/15/unit-testing-with-core-data/</link>
		<comments>http://www.cimgf.com/2012/05/15/unit-testing-with-core-data/#comments</comments>
		<pubDate>Tue, 15 May 2012 21:43:58 +0000</pubDate>
		<dc:creator>Saul Mora</dc:creator>
				<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[MagicalRecord]]></category>
		<category><![CDATA[UnitTesting]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1673</guid>
		<description><![CDATA[Whether you subscribe to Test Driven Development (TDD) or another testing practice, when it comes automated unit testing with Core Data, things can be a little tricky. But if you keep it simple, and take things step by step, you can get up and running with unit testing using Core Data fairly quickly. We&#8217;ll explore [...]]]></description>
			<content:encoded><![CDATA[<p>Whether you subscribe to Test Driven Development (TDD) or another testing practice, when it comes automated unit testing with Core Data, things can be a little tricky. But if you keep it simple, and take things step by step, you can get up and running with unit testing using Core Data fairly quickly. We&#8217;ll explore the what, how and why of unit testing with Core Data. We&#8217;ll also be using the helper library <a href="http://magicalrecord.com">MagicalRecord</a>. MagicalRecord not only lets us get up and running faster, but helps to cut down on the noise in our tests.</p>

<p><span id="more-1673"></span></p>

<h2>Testing Environment</h2>

<p>When you set up a Core Data stack using a file based store (say, using the sqlite store), that file becomes tied to the data model. That is for good reason. Core Data needs to first verify several things before it can use that data store. It must verify the entities have all the attributes the data model expects, as well as to ensure all entities are present in the store. The data and the description of that data must match exactly. However, when you are developing an app using Core Data, this schema changes fast. Adding a new attribute, or even simply changing it&#8217;s type can alter the version hashes enough so that the file version and the model version don&#8217;t match.</p>

<p>All this is to say that using a file based datastore for unit testing is problematic. Even if you were to set up your file based Core Data model to be auto migrating, it&#8217;s still highly likely you&#8217;ll perform a refactoring that is simply not compatible with automigrations. Another likely scenario when testing is that you&#8217;ll want to create simple test data for a single test, or suite of tests, and then delete it.</p>

<p>While testing with a file based Core Data store is possible, it&#8217;s fairly tricky and error prone. Generally, when you setup your test cases, you&#8217;ll want to load your sample set of data. When you&#8217;re finished, you&#8217;ll then want to delete all that data. Unit tests should fail on an error with our application code, not our test infrastructure, setup or teardown code. And besides, I know you&#8217;ve already jumped to the same conclusion I have by now, and that&#8217;s to use an In-Memory persistent store. Not only are there no file deletions to deal with, you will never have to perform a migration. Since during unit testing, you want a temporary store, the in-memory store is a perfect setup.</p>

<blockquote><strong>Note:</strong> Using an in-memory store to perform tests against a Core Data store is not an entirely new concept. <a href="http://twitter.com/secboffin">Graham Lee</a> has also previously <a href="http://iamleeg.blogspot.com/2010/01/unit-testing-core-data-driven-apps-fit.html">described</a> his process and setup for testing Core Data with an in-memory store.</blockquote>

<h2>Quickly Setting up Tests</h2>

<p>Now that we&#8217;ve gone over a little background, let&#8217;s get to how we can use <a href="http://www.magicalrecord.com">MagicalRecord</a> to easily setup our Core Data tests.</p>

<p>As we&#8217;ve discussed previously, MagicalRecord comes with a set of helpers to build a simple Core Data stack for you. We&#8217;ll use one that&#8217;s fairly straight forward:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>MagicalRecord setupCoreDataStackWithInMemoryStore<span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>We&#8217;ll also want to clean up the Core Data stack after some tests, and, yes, MagicalRecord provides a handy cleanup method for you:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>MagicalRecordHelpers cleanUp<span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>Let&#8217;s explore when and where to incorporate these method calls into your tests.</p>

<h2>Testing Frameworks</h2>

<p>Up to this point, the discussion hasn&#8217;t been geared toward any particular testing framework, although the syntax is common to the SenTestingKit testing framework that is now built in (and a first class citizen in Xcode4). However, there are now several testing frameworks now that provide many structural similarities, while improving on the syntax. Let&#8217;s see how things differ across a few of the more popular testing frameworks available for Objective C.</p>

<h3>SenTest, OCUnit, GHUnit</h3>

<p>SenTestingKit and <a href="https://github.com/gabriel/gh-unit">GHUnit</a> offer a very similar experience from a testing perspective. Primarily, you create a new subclass of SenTestCase, or GHTestCase, and author all your tests in methods starting with the word &#8220;<em>test</em>&#8220;. You can also run a method before all tests in the class are performed, or before each method.</p>

<p>Depending on how you set up your tests, you have two options on where to put the simple MagicalRecord setup method. If you want a pristine data store for every test (useful for isolating tests), then you&#8217;ll want to put this method in the setUp method like so:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setUp;
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>MagicalRecord setupCoreDataStackWithInMemoryStore<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>However, there are certain cases where you&#8217;ll need to preload a larger test data set to test against. I would recommend doing this before each and every test as it will only slow your test runs down. And making tests slower can eventually lead to you not running them at all. I recommend setting this up once per test suite:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setUpClass;
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>MagicalRecord setupCoreDataStackWithInMemoryStore<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>And to clean up your stack, simply add a call to the clean up method using the appropriate post-test method, tearDown, or tearDownClass.</p>

<h3>Kiwi, Cedar</h3>

<p><a href="https://github.com/allending/Kiwi">Kiwi</a> and <a href="https://github.com/pivotal/cedar">Cedar</a> are the <a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">Behavior Driven Development (BDD)</a> style frameworks. Rather than methods, you format your tests using blocks, however there are similar mechanics when runnings tests. That is, you also have ways to setup and teardown your test Core Data stack even if the methods aren&#8217;t called setup and teardown. However, with it&#8217;s block type syntax, you can have nested setup calls to <em>beforeAll</em> and <em>beforeEach</em>, <em>afterAll</em> and <em>afterEach</em> (the BDD versions of the setup and teardown methods). You will want to place your calls to set up your test core data stack at an appropriate level within your block contexts.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">describe<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;MyEntity&quot;</span>, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
&nbsp;
  beforeEach<span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>MagicalRecord setupCoreDataStackWithInMemoryStore<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
  afterEach<span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>MagicalRecord cleanUp<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
  it<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;should do something awesome&quot;</span>, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span> <span style="color: #11740a; font-style: italic;">/* Put your test here! */</span> <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;</pre></div></div>


<p>As you can see, setting up and cleaning up after your tests is fairly easy with MagicalRecord.</p>

<h2>Supporting Xcode&#8217;s Unit Test Support</h2>

<p>When using a testing framework like GHUnit, the afore mentioned steps are all that&#8217;s required to get started. However, when it comes to using Xcode&#8217;s built in unit test bundle, there is one extra step required in order to get the stack setup.</p>

<p>When you first need to load up the Core Data stack, you typically use the method:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSManagedObjectModel</span> mergedModelsFromBundle<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>This method, give the parameter of nil, will look in the main bundle, which is generally the application bundle, and look for all data model files, and merge those files into a single Core Data model instance for use when instantiating an NSPersistentStoreCoordinator and it&#8217;s related NSPersistentStore. However, with the Unit Test bundle, this call does not return the correct answer, as <a href="http://iamleeg.blogspot.com/2010/01/unit-testing-core-data-driven-apps-fit.html">documented</a> by Graham Lee. The solution to this problem is simple: we need to specify the correct bundle so that the Core Data stack initialization process can continue on it&#8217;s way. To do this with MagicalRecord, we use the following setUp method for our tests:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setUp;
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>MagicalRecord setDefaultModelFromClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>MagicalRecord setupCoreDataStackWithInMemoryStore<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>The <em>setDefaultModelFromClass:</em> method will perform the solution provided by Graham Lee, which is to load the model from the specified class, which, in turn, is the class of the currently executing test case. And now that we have something more generic, we have the ability to create a very simple boilerplate Core Data unit test case:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">//CoreDataTestCase.h</span>
&nbsp;
<span style="color: #a61390;">@interface</span> CoreDataTestCase <span style="color: #002200;">:</span> SenTestCase
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">//CoreDataTestCase.m</span>
<span style="color: #6e371a;">#import &quot;CoreDataTestCase.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> CoreDataTestCase
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setUp;
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>MagicalRecord setDefaultModelWithClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>MagicalRecord setupCoreDataStackWithInMemoryStore<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>tearDown;
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>MagicalRecord cleanUp<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></div></div>


<p>This means that when you begin authoring unit tests requiring Core Data, you can simply inherit from this base test case, and you&#8217;re ready to start writing tests.</p>

<h2>A Test Case</h2>

<p>First of all, it goes without saying that when you&#8217;re using Core Data, you create a set of custom entity classes, which are subclasses of NSManagedObject.  And, to make your life easier, you should always use <a href="http://rentzsch.github.com/mogenerator/">mogenerator</a> to create your custom entities. This is where your custom logic will live. Let&#8217;s author a sample test:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> SampleTestCase</pre></div></div>



<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setUp;
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>MagicalRecord setDefaultModelWithClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>MagicalRecord setupCoreDataStackWithInMemoryStore<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>tearDown;
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>MagicalRecord cleanUp<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>testSomeCalculationOnMyEntity;
<span style="color: #002200;">&#123;</span>
	MyEntity <span style="color: #002200;">*</span>testEntity <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>MyEntity MR_createEntity<span style="color: #002200;">&#93;</span>;
	<span style="color: #a61390;">float</span> expectedValue <span style="color: #002200;">=</span> …;
	STAssert<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>testEntity customCalculation<span style="color: #002200;">&#93;</span> <span style="color: #002200;">==</span> expectedValue, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;expected a good calculation&quot;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></div></div>


<p>The <em>MR_createEntity</em> method will use the default context that was set up when the <em>setupCoreDataStackWithInMemoryStore</em> method was called earlier on in the test run. This makes for clean tests based on Core Data, but doesn&#8217;t let the Core Data syntax get in the way of expressing the intent of the test. And, when the test has completed, this sample entity will be deleted by virtue of the store being released from memory, so that the next test can have a clean slate with which to work.</p>

<h2>Conclusion</h2>

<p>And with that, you have an extremely simple and fast way to get a test environment setup for unit testing with Core Data. What I enjoy most about this setup is that when authoring unit tests which require Core Data, I am not focused on the details of setting up and tearing down Core Data. Rather, I&#8217;m focused on a single entity, and the things it requires in order to work properly. A sample set of unit tests which, in turn, test MagicalRecord itself are included in the <a href="http://magicalrecord.com">MagicalRecord source</a> on github.</p>

<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2012/05/15/unit-testing-with-core-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extending NSData and (not) Overriding dealloc</title>
		<link>http://www.cimgf.com/2012/02/17/extending-nsdata-and-not-overriding-dealloc/</link>
		<comments>http://www.cimgf.com/2012/02/17/extending-nsdata-and-not-overriding-dealloc/#comments</comments>
		<pubDate>Fri, 17 Feb 2012 05:53:29 +0000</pubDate>
		<dc:creator>Tom Harrington</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[System Programming]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1686</guid>
		<description><![CDATA[A couple of weeks ago Matt Long was having a problem with an app running out of memory. He had a ginormous data file he needed to load up and process, and that memory hit was more than the app could bear. It would load just fine, into an NSData, but before he could finish [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of weeks ago Matt Long was having a problem with an app running out of memory. He had a ginormous data file he needed to load up and process, and that memory hit was more than the app could bear. It would <em>load</em> just fine, into an NSData, but before he could finish with it the app would run short of memory and die.</p>

<p>Until recently the obvious thing would have been to tell NSData to create a memory-mapped instance. Given <code>NSString *path</code> pointing to a file, you could create an NSData with almost no memory hit regardless of file size by creating it as:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>data <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSData</span> dataWithContentsOfMappedFile<span style="color: #002200;">:</span>path<span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>Starting with iOS 5 though, this method has been deprecated. Instead, what you&#8217;re supposed to do is:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
<span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>data <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSData</span> dataWithContentsOfFile<span style="color: #002200;">:</span>path options<span style="color: #002200;">:</span>NSDataReadingMappedAlways error<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>So, fine, whatever, it&#8217;s a different call, so what? Well, it wasn&#8217;t working. Instruments was showing that the app was taking the full memory hit when the NSData was created. Mapping wasn&#8217;t working despite using NSDataReadingMapped<em>Always</em>. So what could he do? The wheels of my mind started turning.</p>

<p><span id="more-1686"></span></p>

<h2>Memory mapped files</h2>

<p>But first, a brief aside about memory mapping.</p>

<p>Memory mapping is a cool Unix trick that lets you load a file into memory without, as it were, actually loading it into memory. It&#8217;s a way of using virtual memory to your advantage when you have a really big file and you don&#8217;t want to spend the RAM on it.</p>

<p>Contrary to common misconception, iOS does have virtual memory. It just doesn&#8217;t create swap files. But the full power of virtual memory is at your disposal. When you create a memory mapped file, the operating system gives you a memory pointer that you can use to access the file&#8217;s data. It&#8217;s as if the file was already loaded into memory but had since been swapped back out. When you access bytes in the memory map, data blocks are selectively read from the file as needed, and disposed of when they aren&#8217;t.</p>

<p>In short, it&#8217;s <strong>exactly</strong> what you need when your data file is too big to load, and if NSData won&#8217;t do it, I&#8217;ll just have to force it.</p>

<h2>By the power of <del datetime="2012-02-14T05:50:40+00:00">Greyskull</del> Unix!</h2>

<p>To create memory mapped files NSData is making use of iOS&#8217;s excellent Unix core. NSData isn&#8217;t actually mapping files itself, instead it&#8217;s using the Unix <code>mmap(2)</code> call. I can use that too. Given an <code>NSString *path</code> pointing to a file, you can create an memory mapped file like this:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Get an fd</span>
<span style="color: #a61390;">int</span> fd <span style="color: #002200;">=</span> open<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>path fileSystemRepresentation<span style="color: #002200;">&#93;</span>, O_RDONLY<span style="color: #002200;">&#41;</span>;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>fd &lt; <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">return</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// Get file size</span>
<span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>fileAttributes <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSFileManager</span> defaultManager<span style="color: #002200;">&#93;</span> attributesOfItemAtPath<span style="color: #002200;">:</span>path error<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>fileAttributes <span style="color: #002200;">==</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    close<span style="color: #002200;">&#40;</span>fd<span style="color: #002200;">&#41;</span>;
    <span style="color: #a61390;">return</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span>
<span style="color: #400080;">NSNumber</span> <span style="color: #002200;">*</span>fileSize <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>fileAttributes objectForKey<span style="color: #002200;">:</span>NSFileSize<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// mmap</span>
<span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>mappedFile;
mappedFile <span style="color: #002200;">=</span> mmap<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #002200;">&#91;</span>fileSize intValue<span style="color: #002200;">&#93;</span>, PROT_READ, MAP_FILE|MAP_PRIVATE, fd, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
close<span style="color: #002200;">&#40;</span>fd<span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>mappedFile <span style="color: #002200;">==</span> MAP_FAILED<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Map failed, errno=%d, %s&quot;</span>, <span style="color: #a61390;">errno</span>, <span style="color: #a61390;">strerror</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">errno</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #a61390;">return</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>To call <code>mmap(2)</code> this code first gets a file descriptor for the file via <code>open(2)</code>. That, combined with the file&#8217;s size, is enough to create the memory mapping. Once the mapping exists, the code disposes of the file descriptor via <code>close(2)</code>. At this point, <code>mappedFile</code> points to a bunch of bytes which is more or less indistinguishable from what you&#8217;d get if you had actually read the file into memory. And NSData knows how to use byte blobs.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Create the NSData</span>
<span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>mappedData <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSData</span> dataWithBytesNoCopy<span style="color: #002200;">:</span>mappedFile length<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>fileSize intValue<span style="color: #002200;">&#93;</span> freeWhenDone<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>I can convert the pointer into an NSData using one of NSData&#8217;s longer convenience initializers. Why create it this way? Because (a) I don&#8217;t want to copy the bytes, since that would negate the advantage of memory mapping, and (b) I don&#8217;t want NSData to try and clean up those bytes when it gets deallocated.</p>

<h2>The Complication</h2>

<p>But I <em>do</em> need to clean up those bytes. I just don&#8217;t want NSData to do it, because it doesn&#8217;t know the bytes came from a mapping and won&#8217;t clean them up properly. I need to remove the memory map. What needs to happen is a call to <code>munmap(2)</code> when the NSData deallocates.</p>

<p>So, what does the code need to look like in order to make this call? Ideally the cleanup should happen automatically. I could just call <code>munmap(2)</code> directly. But that would mean keeping the map pointer around and then making a separate call. All to clean up what is, conceptually at least, an internal data structure. It would work but it&#8217;s ugly.</p>

<p>Anyway, with ARC there&#8217;s the chance that I&#8217;d make the call before the NSData deallocated, with disastrous results. Really what I&#8217;d like to do is wrap the code above into a convenient API where you can create the mapped NSData, use it, and dispose of it normally. Any extra cleanup should just <em>happen</em>. After all this is Cocoa and it&#8217;s supposed to work well.</p>

<p>My first thought was to subclass NSData and have the subclass store the map pointer. Then the subclass could call <code>munmap(2)</code> from its <code>-dealloc</code> method. But NSData is a class cluster, and subclassing class clusters is kind of a pain in the ass. Class clusters are a bunch of classes that masquerade as a specific public class. Examples include NSString, NSArray, and others. And of course NSData.</p>

<p>You may recall that <code>-init</code> is not required to return an instance of the class you thought you were creating. That is, if you call</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">Foo <span style="color: #002200;">*</span>myFoo <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>Foo alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>&#8230;the resulting object is not required to actually be an instance of <code>Foo</code>. Class clusters are a case where this happens. When you create an NSData, what you&#8217;re probably getting is an instance of something like NSConcreteData. That class isn&#8217;t documented but it acts like an NSData and you generally can&#8217;t tell the difference.</p>

<p>Subclassing class clusters can be challenging. You need to override all of the superclass&#8217;s <em>primitive</em> methods. Those are the methods that access the object&#8217;s data directly. NSData&#8217;s primitive methods aren&#8217;t documented, either. If you don&#8217;t get them all you&#8217;ll get crashes with fairly incomprehensible exceptions like:</p>

<p><pre>
Catchpoint 6 (exception thrown).2012-02-07 21:04:10.620 MapTest[9719:f803] <strong>*
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '</strong>*
initialization method -initWithBytes:length:copy:freeWhenDone:bytesAreVM: cannot be
sent to an abstract object of class NSMappedData: Create a concrete instance!'
</pre></p>

<p>I could probably figure out what the primitive methods are but doing that without documentation has a strong whiff of reverse engineering. I&#8217;d really rather avoid that. But how else can I make sure the call happens? And can I make it happen automatically?</p>

<h2>Adding dealloc code in a category</h2>

<p>The method I had in mind for creating mapped NSData instances would look something like:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>dataWithContentsOfReallyMappedFile<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>path;</pre></div></div>


<p>I could put that in a category except that to make it easy to use I&#8217;d need to have some code to <code>-dealloc</code> that could call <code>munmap(2)</code>. That&#8217;s more or less what what I&#8217;m going to do.</p>

<p>Wait, what? You can&#8217;t override <code>-dealloc</code> in a category. But thanks to associated objects, you don&#8217;t have to. If have some object A, and you associate a secondary object B with it, then when A gets deallocated, B will too. If you have something you really need to happen when A gets deallocated, you can call that code from B&#8217;s dealloc method. Bingo, deallocation code for A that runs in a separate class. As long as you don&#8217;t need to access A&#8217;s private internal data, anyway.</p>

<p>This could be pretty useful so I decided to write it as a generic system that I could use with memory mapped NSData instances but that isn&#8217;t tied to them. I created a generic class called <code>DeallocationHandler</code>:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> DeallocHandler <span style="color: #002200;">:</span> <span style="color: #400080;">NSObject</span>
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>readwrite, copy<span style="color: #002200;">&#41;</span> <span style="color: #a61390;">void</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span>theBlock<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> DeallocHandler
<span style="color: #a61390;">@synthesize</span> theBlock;
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>dealloc
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>theBlock <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        theBlock<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>


<p>This doesn&#8217;t do much on its own. Give it a block and it will run the block when it gets deallocated. Where it gets interesting is when you use it in a category on NSObject:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">static</span> <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>deallocArrayKey <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">&quot;deallocArrayKey&quot;</span>;
&nbsp;
<span style="color: #a61390;">@implementation</span> <span style="color: #400080;">NSObject</span> <span style="color: #002200;">&#40;</span>deallocBlock<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>addDeallocBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>theBlock;
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSMutableArray</span> <span style="color: #002200;">*</span>deallocBlocks <span style="color: #002200;">=</span> objc_getAssociatedObject<span style="color: #002200;">&#40;</span>self, <span style="color: #002200;">&amp;</span>deallocArrayKey<span style="color: #002200;">&#41;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>deallocBlocks <span style="color: #002200;">==</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        deallocBlocks <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableArray</span> array<span style="color: #002200;">&#93;</span>;
        objc_setAssociatedObject<span style="color: #002200;">&#40;</span>self, <span style="color: #002200;">&amp;</span>deallocArrayKey, deallocBlocks, OBJC_ASSOCIATION_RETAIN_NONATOMIC<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span>
    DeallocHandler <span style="color: #002200;">*</span>handler <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>DeallocHandler alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>handler setTheBlock<span style="color: #002200;">:</span>theBlock<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>deallocBlocks addObject<span style="color: #002200;">:</span>handler<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>


<p>The <code>-addDeallocBlock:</code> method associates an array of DeallocationHandler instances with the target object. Each DeallocationHandler in turn has a block provided by the caller. The upshot is that, when the target object deallocates, all of those blocks will be run. This lets me attach dealloc-time code to any object. In fact I could add as many blocks as I needed and they&#8217;d run in order.</p>

<p>One minor caveat is that you <em>really</em> need to watch the memory references in these blocks. If the block references the object that it&#8217;s attached to, then the circular references mean that the object won&#8217;t ever get deallocated. This is just standard safe block usage, though.</p>

<h2>Getting back to NSData</h2>

<p>Using the deallocation block scheme I can add a block calling <code>munmap(2)</code> to my NSData object by adding this code right after I create it:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>mappedData addDeallocBlock<span style="color: #002200;">:^</span><span style="color: #002200;">&#123;</span>
    munmap<span style="color: #002200;">&#40;</span>mappedFile, <span style="color: #002200;">&#91;</span>fileSize intValue<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>This leaves me with two categories instead of just one, but in the end I can just create mapped NSData instances and not bother with special cleanup code in my app.</p>

<h2>Conclusion</h2>

<p>Never forget that Apple&#8217;s APIs are not a menu of possibilities. They&#8217;re a set of tools, but you can and should build your own tools when you need them. Unix is available on iOS, so don&#8217;t be afraid to use it. In this example we&#8217;ve seen how to:</p>

<ul>
<li>Add deallocation code to any object without subclassing.</li>
<li>Create memory mapped NSData instances even though the official API has been deprecated and the new one doesn&#8217;t currently work.</li>
</ul>

<p>The code described in this post can be found at <a href="https://github.com/atomicbird/atomictools">Github</a>.</p>

<p><strong>Update:</strong> In response to queries I&#8217;ve had via Twitter, please be aware that the code described here assumes that you&#8217;re using ARC. If you&#8217;re not using ARC you&#8217;ll need to add a line that releases the new DeallocHandler before <code>-addDeallocBlock:</code> returns.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2012/02/17/extending-nsdata-and-not-overriding-dealloc/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>A phased approach to sandboxing</title>
		<link>http://www.cimgf.com/2012/02/04/a-phased-approach-to-sandboxing/</link>
		<comments>http://www.cimgf.com/2012/02/04/a-phased-approach-to-sandboxing/#comments</comments>
		<pubDate>Sun, 05 Feb 2012 04:04:07 +0000</pubDate>
		<dc:creator>Fraser Hess</dc:creator>
				<category><![CDATA[AppStore]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1655</guid>
		<description><![CDATA[With the March 1st start date approaching when sandboxing becomes a requirement for submissions to the Mac App Store, I&#8217;ve been considering my options. I have 2 products, one of which was easy to sandbox and the other, well, not so much. When I say &#8220;easy to sandbox&#8221;, I mean it fit neatly in the [...]]]></description>
			<content:encoded><![CDATA[<p>With the March 1st start date approaching when sandboxing becomes a requirement for submissions to the Mac App Store, I&#8217;ve been considering my options.<span id="more-1655"></span>
I have 2 products, one of which was easy to sandbox and the other, well, not so much. When I say &#8220;easy to sandbox&#8221;, I mean it fit neatly in the &#8220;permanent&#8221; entitlements and doesn&#8217;t need any files migrated into the sandbox, besides it&#8217;s preferences, which is done automatically for you.</p>

<p>Now, my sandbox technical challenges are not DOA. Some apps and classes of app are in effect outlawed by the sandbox rules. I feel for the developers of those apps, but fortunately for me, I&#8217;m not facing that.</p>

<p>My challenges fall more the &#8220;a few features may need rethinking and rewriting&#8221; category. At first I expected to have a long hiatus between updates while I worked on these features. But instead, I&#8217;m easing this transition by implementing sandboxing in 2 phases.</p>

<ol>
<li>Add sandboxing to the MAS build of my app. Use temporary entitlements where necessary to maintain functionality. Make minor adjustments to run inside the sandbox. Submit an update to test the approval process.</li>
<li>Begin the rethinking and rewriting of sandbox-incompliant features.</li>
</ol>

<p>Advantages I can see to this approach:</p>

<ul>
<li>I can continue to fix bugs, and issue updates beyond March 1st without a long hiatus.</li>
<li>Development on my app does not appear quiescent.</li>
<li>By submitting early, I&#8217;m not testing approval when trying to push out a needed bug fix.</li>
<li>By using temporary entitlements, I signal to Apple that these are needed and useful.</li>
<li>I buy more time to rethink and rewrite.</li>
</ul>

<p>Sandboxing is a great leap in application security but every app has a different story when it comes to the implementation details. I encourage <a href="http://bugreport.apple.com/">bug reporting</a>. It&#8217;s important to explain to the Apple engineers what we developers need. And I hope that some of the thoughts here help you navigate the challenges.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2012/02/04/a-phased-approach-to-sandboxing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Handling incoming JSON redux</title>
		<link>http://www.cimgf.com/2012/01/11/handling-incoming-json-redux/</link>
		<comments>http://www.cimgf.com/2012/01/11/handling-incoming-json-redux/#comments</comments>
		<pubDate>Wed, 11 Jan 2012 15:00:37 +0000</pubDate>
		<dc:creator>Tom Harrington</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[System Programming]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1573</guid>
		<description><![CDATA[A few months ago I wrote here about a generic approach to safely take incoming JSON and save values to Core Data object. The goals of that code were twofold: Provide a safe, generic alternative to Cocoa&#8217;s -setValuesForKeysWithDictionary: for use with NSManagedObject and its subclasses Handle cases where JSON data didn&#8217;t match up with what [...]]]></description>
			<content:encoded><![CDATA[<p>A few months ago I wrote here about <a href="http://www.cimgf.com/2011/06/02/saving-json-to-core-data/">a generic approach to safely take incoming JSON and save values to Core Data object</a>. The goals of that code were twofold:</p>

<ol>
    <li>Provide a safe, generic alternative to Cocoa&#8217;s <code>-setValuesForKeysWithDictionary:</code> for use with NSManagedObject and its subclasses</li>
    <li>Handle cases where JSON data didn&#8217;t match up with what the managed objects expected. Getting a string where you expect a numeric value, or vice versa, for example, or getting a string representation of a date when you want a real NSDate object.</li>
</ol>

<p>The first item was the most important. It&#8217;s tempting to use <code>-setValuesForKeysWithDictionary:</code> to transfer JSON to a model object in one step. The method runs through the dictionary and calls <code>-setValue:forKey:</code> on the target object for every entry. It has a fatal flaw though, in that it doesn&#8217;t check to see if the target object actually has a key before trying to set it. Using this method when you don&#8217;t have absolute control over the dictionary contents is an invitation to unknown key exceptions and nasty app crashes.</p>

<p>Fixing this for managed objects was relatively easy because Core Data provides convenient Objective-C introspection methods. The general approach was:</p>

<ul>
    <li>Get a list of the target object&#8217;s attributes</li>
    <li>For each attribute, see if the incoming dictionary has an entry. If so,</li>
<ul>
    <li>Compare the incoming type to the expected type, and convert if necessary.</li>
    <li>Call <code>-setValue:forKey:</code> with that key and its value.</li>
</ul>
</ul>

<p>And then just last week I had the thought, wouldn&#8217;t it be nice if this worked for <em>any</em> object, not just for managed objects?</p>

<p><span id="more-1573"></span></p>

<h2>Objective-C introspection</h2>

<p>Since Objective-C is dynamic, pretty much everything you&#8217;d want to know about a class is available at run time. I&#8217;m not just talking about methods like <code>-respondsToSelector:</code> and <code>-isKindOfClass:</code>, though those are extremely useful. You can go much, much deeper than that, inspecting (and even changing) every aspect of a class&#8217;s implementation. Much of this happens via C function calls rather than Objective-C method calls. The Objective-C runtime is not actually written in Objective-C, and it&#8217;s the runtime that has the information.</p>

<p>To update the code for use with objects that don&#8217;t inherit from NSManagedObject the new code looks through the properties declared on a class and uses those to run through the incoming JSON. The general approach is the same but the implementation uses NSObject properties instead of NSEntityDescription attributes.</p>

<p>It&#8217;s also possible to look through the instance variables instead of the properties. Often this would amount to the same thing. Where they differ is when the backing ivar has a different name, i.e. when you&#8217;re using something like:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@synthesize</span> foo <span style="color: #002200;">=</span> __myReallyBizarrePrivateName____;</pre></div></div>


<p>In that case iterating over properties would find <code>foo</code> while iterating over instance variables would find <code>__myReallyBizarrePrivateName____</code>. Either is valid but I&#8217;m going with the properties because (at least for me) they&#8217;re more likely to match up with the JSON keys.</p>

<h2>First pass: iterating over properties</h2>

<p>A simple version that meets requirement #1 looks like this:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setValuesForKeysWithJSONDictionary<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>keyedValues dateFormatter<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDateFormatter</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>dateFormatter
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">unsigned</span> <span style="color: #a61390;">int</span> propertyCount;
    objc_property_t <span style="color: #002200;">*</span>properties <span style="color: #002200;">=</span> class_copyPropertyList<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>self class<span style="color: #002200;">&#93;</span>, <span style="color: #002200;">&amp;</span>propertyCount<span style="color: #002200;">&#41;</span>;
&nbsp;
    <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> i<span style="color: #002200;">=</span><span style="color: #2400d9;">0</span>; i&lt;propertyCount; i<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        objc_property_t property <span style="color: #002200;">=</span> properties<span style="color: #002200;">&#91;</span>i<span style="color: #002200;">&#93;</span>;
        <span style="color: #a61390;">const</span> <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>propertyName <span style="color: #002200;">=</span> property_getName<span style="color: #002200;">&#40;</span>property<span style="color: #002200;">&#41;</span>;
        <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>keyName <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithUTF8String<span style="color: #002200;">:</span>propertyName<span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #a61390;">id</span> value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>keyedValues objectForKey<span style="color: #002200;">:</span>keyName<span style="color: #002200;">&#93;</span>;
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>value <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            <span style="color: #002200;">&#91;</span>self setValue<span style="color: #002200;">:</span>value forKey<span style="color: #002200;">:</span>keyName<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#125;</span>
    <span style="color: #a61390;">free</span><span style="color: #002200;">&#40;</span>properties<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>This starts with a call to <code>class_copyPropertyList()</code>, which gets a C-style array of property declarations for the requested class. The <code>propertyCount</code> argument indicates how many properties are in the array. The array contains zero or more <code>objc_property_t</code> entries, which is an opaque structure.</p>

<p>The code iterates through this array. For each one it uses <code>property_getName</code> to get the property name as a C-style string. Then it converts this to an NSString and uses that to look up entries in the incoming dictionary. And, <em>voila</em>, we&#8217;re using the class&#8217;s own properties to look up values in the dictionary instead of the other way around.</p>

<p>A final detail&#8211; unusual in Objective-C code&#8211; is the call to <code>free()</code>. Since <code>class_copyPropertyList()</code> has <em>copy</em> in its name, the calling code is responsible for disposing of the returned data. And since it&#8217;s a C call, this needs to be done C style. This call would need to be there even if the project were using ARC.</p>

<h2>Back to Core Data, briefly</h2>

<p>The great thing about this solution is that it&#8217;s not the non-managed-object alternative to the previous version, it&#8217;s a direct replacement. This approach works just as well on managed objects as on other objects&#8211; provided, that is, that you create custom subclasses of <code>NSManagedObject</code> for your entities that declare properties for managed object attributes. So long as the properties exist, the code works. If you&#8217;re using Xcode or <a href="http://rentzsch.github.com/mogenerator/">mogenerator</a> to generate your managed object subclasses, you&#8217;re covered. If you aren&#8217;t creating custom subclasses, first of all, why not? But in that case this approach won&#8217;t work since <code>NSManagedObject</code> doesn&#8217;t have the necessary property declarations.</p>

<h2>Does it have to be like this?</h2>

<p>Some of you may have noticed that it&#8217;s possible to do the same thing without any mucking about with the runtime by doing something like this:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;">    <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>key <span style="color: #a61390;">in</span> keyedValues<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #a61390;">@try</span> <span style="color: #002200;">&#123;</span>
            <span style="color: #002200;">&#91;</span>self setValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>keyedValues objectForKey<span style="color: #002200;">:</span>key<span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span>key<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#125;</span>
        <span style="color: #a61390;">@catch</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSException</span> <span style="color: #002200;">*</span>exception<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            <span style="color: #11740a; font-style: italic;">// Do nothing</span>
        <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>In this case the dictionary keys still drive the action, but exception handling means the code doesn&#8217;t crash on unknown keys. So why bother then? Because of requirement #2 above. Coercing JSON into appropriate data types is going to require introspection. With this simplified approach you don&#8217;t crash, but you also don&#8217;t get type conversions. If not crashing is all you&#8217;re interested in, this works just as well and is probably faster. It&#8217;s certainly simpler anyway. It&#8217;s not going to do what I need though.</p>

<h2>JSON Fixes</h2>

<p>To meet requirement #2 the code needs to go deeper. As with the Core Data implementation, it needs to look up the expected value for the property and compare that to the type of the incoming data. To do this I&#8217;ll expand the <code>if</code> block beginning on line 12 above to look like this:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>value <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>typeEncoding <span style="color: #002200;">=</span> <span style="color: #a61390;">NULL</span>;
    typeEncoding <span style="color: #002200;">=</span> property_copyAttributeValue<span style="color: #002200;">&#40;</span>property, <span style="color: #bf1d1a;">&quot;T&quot;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>typeEncoding <span style="color: #002200;">==</span> <span style="color: #a61390;">NULL</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #a61390;">continue</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #a61390;">switch</span> <span style="color: #002200;">&#40;</span>typeEncoding<span style="color: #002200;">&#91;</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'@'</span><span style="color: #002200;">:</span>
        <span style="color: #002200;">&#123;</span>
            <span style="color: #11740a; font-style: italic;">// Object</span>
            <span style="color: #a61390;">Class</span> class <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">strlen</span><span style="color: #002200;">&#40;</span>typeEncoding<span style="color: #002200;">&#41;</span> &gt;<span style="color: #002200;">=</span> <span style="color: #2400d9;">3</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
                <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>className <span style="color: #002200;">=</span> strndup<span style="color: #002200;">&#40;</span>typeEncoding<span style="color: #002200;">+</span><span style="color: #2400d9;">2</span>, <span style="color: #a61390;">strlen</span><span style="color: #002200;">&#40;</span>typeEncoding<span style="color: #002200;">&#41;</span><span style="color: #002200;">-</span><span style="color: #2400d9;">3</span><span style="color: #002200;">&#41;</span>;
                class <span style="color: #002200;">=</span> NSClassFromString<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithUTF8String<span style="color: #002200;">:</span>className<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
            <span style="color: #002200;">&#125;</span>
            <span style="color: #11740a; font-style: italic;">// Check for type mismatch, attempt to compensate</span>
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>class isSubclassOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">&#91;</span>value isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
                value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>value stringValue<span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>class isSubclassOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">&#91;</span>value isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
                <span style="color: #11740a; font-style: italic;">// If the ivar is an NSNumber we really can't tell if it's intended as an integer, float, etc.</span>
                <span style="color: #400080;">NSNumberFormatter</span> <span style="color: #002200;">*</span>numberFormatter <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumberFormatter</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
                <span style="color: #002200;">&#91;</span>numberFormatter setNumberStyle<span style="color: #002200;">:</span>NSNumberFormatterDecimalStyle<span style="color: #002200;">&#93;</span>;
                value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>numberFormatter numberFromString<span style="color: #002200;">:</span>value<span style="color: #002200;">&#93;</span>;
                <span style="color: #002200;">&#91;</span>numberFormatter release<span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>class isSubclassOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSDate</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">&#91;</span>value isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">&#40;</span>dateFormatter <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
                value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>dateFormatter dateFromString<span style="color: #002200;">:</span>value<span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span>
&nbsp;
            <span style="color: #a61390;">break</span>;
        <span style="color: #002200;">&#125;</span>
&nbsp;
        <span style="color: #a61390;">default</span><span style="color: #002200;">:</span>
        <span style="color: #002200;">&#123;</span>
            <span style="color: #a61390;">break</span>;
        <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#91;</span>self setValue<span style="color: #002200;">:</span>value forKey<span style="color: #002200;">:</span>keyName<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">free</span><span style="color: #002200;">&#40;</span>typeEncoding<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>The runtime provides information about properties via the call to <code> property_copyAttributeValue()</code> on line 3. The first argument is the property of interest. The second one can have a bunch of different values depending on what you want to look up. A &#8220;T&#8221; requests a C-style string that describes the property type. For full details on what you can do with the second argument, see the (somewhat out of date as of this writing) <a href="http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html">&#8220;Declared Properties&#8221; section of Apple&#8217;s Objective-C Runtime Programming Guide</a>.</p>

<p>If the property type is a pointer to a class, the return value will be something like <code>T@"NSNumber"</code>, <code>T@"NSString"</code>, <code>T@"MyClass"</code>, etc. The next thing the code does then is to check for a leading <code>@</code> and, if found, set about getting the <code>Class</code> that the type string names. This happens in lines 12-16. The code strips off the <code>@</code> and the quotes, converts to <code>NSString</code>, and uses <code>NSClassFromString</code> to get the <code>Class</code>.</p>

<p>The rest of this code is remarkably similar to the Core Data version, looking for type mismatches and converting the incoming value where needed. The chief difference is that it uses <code>-isSubclassOfClass:</code> to check on the expected type of the property instead of looking at the Core Data-specific <code>NSAttributeType</code>.</p>

<p>Except for one important difference. For numeric properties, the Core Data attribute type would indicate whether a floating point or integer value was expected. With <code>NSNumber</code> we have no way of knowing. So the code uses <code>NSNumberFormatter</code> to parse incoming strings and leaves it at that. If this kind of mismatch occurs then there are bigger problems anyway. You could change the code to round a <code>float</code> to an <code>int</code>, but is that actually going to be a valid result? Maybe, maybe not.</p>

<p>The type comparisons in this code could go on forever but in this case the code is specifically looking for problems that sometimes crop up with JSON.</p>

<p>Since <code>property_copyAttributeValue()</code> has <em>copy</em> in its name, this block adds another call to <code>free()</code> to clean up after itself.</p>

<h2>Handling primitives</h2>

<p>But what if the expected value is not an object at all? What if it&#8217;s a primitive <code>int</code>? Fortunately <code>property_copyAttributeValue()</code> covers that case as well. In this case the type encoding string is shorter, with values like <code>Ti</code> for <code>int</code>, <code>Tf</code> for <code>float</code>, <code>TQ</code> for <code>unsigned long long</code>, etc (again, see Apple&#8217;s docs for a full list).</p>

<p>With this information, the <code>switch</code> statement above can be expanded with a few more cases.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;">        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'i'</span><span style="color: #002200;">:</span> <span style="color: #11740a; font-style: italic;">// int</span>
        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'s'</span><span style="color: #002200;">:</span> <span style="color: #11740a; font-style: italic;">// short</span>
        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'l'</span><span style="color: #002200;">:</span> <span style="color: #11740a; font-style: italic;">// long</span>
        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'q'</span><span style="color: #002200;">:</span> <span style="color: #11740a; font-style: italic;">// long long</span>
        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'I'</span><span style="color: #002200;">:</span> <span style="color: #11740a; font-style: italic;">// unsigned int</span>
        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'S'</span><span style="color: #002200;">:</span> <span style="color: #11740a; font-style: italic;">// unsigned short</span>
        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'L'</span><span style="color: #002200;">:</span> <span style="color: #11740a; font-style: italic;">// unsigned long</span>
        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'Q'</span><span style="color: #002200;">:</span> <span style="color: #11740a; font-style: italic;">// unsigned long long</span>
        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'f'</span><span style="color: #002200;">:</span> <span style="color: #11740a; font-style: italic;">// float</span>
        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'d'</span><span style="color: #002200;">:</span> <span style="color: #11740a; font-style: italic;">// double</span>
        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'B'</span><span style="color: #002200;">:</span> <span style="color: #11740a; font-style: italic;">// BOOL</span>
        <span style="color: #002200;">&#123;</span>
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>value isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
                <span style="color: #400080;">NSNumberFormatter</span> <span style="color: #002200;">*</span>numberFormatter <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumberFormatter</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
                <span style="color: #002200;">&#91;</span>numberFormatter setNumberStyle<span style="color: #002200;">:</span>NSNumberFormatterDecimalStyle<span style="color: #002200;">&#93;</span>;
                value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>numberFormatter numberFromString<span style="color: #002200;">:</span>value<span style="color: #002200;">&#93;</span>;
                <span style="color: #002200;">&#91;</span>numberFormatter release<span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span>
            <span style="color: #a61390;">break</span>;
        <span style="color: #002200;">&#125;</span>
&nbsp;
        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'c'</span><span style="color: #002200;">:</span> <span style="color: #11740a; font-style: italic;">// char</span>
        <span style="color: #a61390;">case</span> <span style="color: #bf1d1a;">'C'</span><span style="color: #002200;">:</span> <span style="color: #11740a; font-style: italic;">// unsigned char</span>
        <span style="color: #002200;">&#123;</span>
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>value isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
                <span style="color: #a61390;">char</span> firstCharacter <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>value characterAtIndex<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>;
                value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithChar<span style="color: #002200;">:</span>firstCharacter<span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span>
            <span style="color: #a61390;">break</span>;
        <span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>The first half of this, up to line 20, handles all the numeric types. As with the previous code block there&#8217;s no attempt to work out floating point/integer conflicts since it&#8217;s impossible to know how to handle this in the general case. It would be possible to break this up into more specific checks, say by using <code>-[NSString intValue]</code> when an integer result is expected and hope for valid data. But the code above handles the case where you actually have an integer value, and if you don&#8217;t have one then again, you have bigger problems.</p>

<p>The rest of this block handles a primitive <code>char</code> property by taking the first character in the incoming string. Longer strings can&#8217;t be stored in a <code>char</code> anyway, so this is the best approach.</p>

<p>In both cases the conversion results in an <code>NSNumber</code> instead of a primitive type. That&#8217;s OK though&#8211; <code>-setValue:forKey:</code> has our back here and will unbox the object for us.</p>

<h2>Conclusion</h2>

<p>Using this approach makes it a lot easier to deal with web services. You can&#8217;t always rely on the results matching what you expect (or what&#8217;s documented). Inspecting classes at run time takes a more defensive approach to dealing with data you can&#8217;t control.</p>

<p>A category on NSObject that implements this code can be found at <a href="https://gist.github.com/1592634">github</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2012/01/11/handling-incoming-json-redux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parent Watching Its Child</title>
		<link>http://www.cimgf.com/2011/10/14/parent-watching-its-child/</link>
		<comments>http://www.cimgf.com/2011/10/14/parent-watching-its-child/#comments</comments>
		<pubDate>Fri, 14 Oct 2011 10:28:19 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Core Data]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1542</guid>
		<description><![CDATA[Recently on StackOverflow I have seen several questions regarding the desire for a parent Entity to be updated whenever an attribute within the child has changed. There are several different ways to solve this problem. The easiest is to have the child ping the parent whenever it changes and then the parent can update any [...]]]></description>
			<content:encoded><![CDATA[<p>Recently on <a href="http://stackoverflow.com">StackOverflow</a> I have seen several questions regarding the desire for a parent Entity to be updated whenever an attribute within the child has changed.</p>

<p>There are several different ways to solve this problem.  The easiest is to have the child ping the parent whenever it changes and then the parent can update any values it needs to as a result of that ping.
<span id="more-1542"></span>
Another solution that I considered was to have the parent observe the property on each child.  Of course this requires additional code to handle when a child is removed from the parent and when a new child is added to the parent.  Lots of code to manage and the potential for fragility is rather high.</p>

<p>The most interesting solution that I offered was to have the parent watch for change notifications and react to them.  It is this solution that I will discuss in a little more depth.</p>

<h2>Change Notifications</h2>

<p>Core Data produces several different notifications during its lifecycle.  The most commonly used notification is <code>NSManagedObjectContextDidSaveNotification</code>.  Whenever a <code>NSManagedObjectContext</code> saves it will fire two notifications, one before the save and one after the save.  The one before the save does not contain any direct information about what is going to be saved although you can discover it yourself.</p>

<p>The second one, <code>NSManagedObjectContextDidSaveNotification</code> contains a reference to each entity that it saved; whether they are newly inserted entities, updated entities or deleted entities.</p>

<p>There is another notification that is not used nearly as often; <code>NSManagedObjectContextObjectsDidChangeNotification</code>.  This notification is significantly more chatty than the other two.  It potentially can fire every time an entity changes.  More specifically it will fire at the end of each run loop where an entity has changed.  While this notification is more chatty, it is more useful for this purpose.</p>

<h2>Why use NSManagedObjectContextObjectsDidChangeNotification?</h2>

<p>Of the three, the <code>NSManagedObjectContextObjectsDidChangeNotification</code> is the most useful for a parent/child monitoring.  Both <code>NSManagedObjectContextDidSaveNotification</code> and <code>NSManagedObjectContextWillSaveNotification</code> only fire when a <code>NSManagedObjectContext</code> has been asked to save.  A save can be a very rare event; possibly only once during the life of the application.</p>

<p>However, <code>NSManagedObjectContextObjectsDidChangeNotification</code> fires frequently enough that we can use it without having to worry about when a save is going to occur.  We can use it during the life of the application and keep a parent updated to the status of its children.</p>

<h2>An Example</h2>

<p>A common example that I like to use while I am testing these theories is my very simple RSS reader. Those who have watched my <a href="http://ideveloper.tv/video/coredatacourse.html">Core Data videos</a> are familiar with Zeader.</p>

<p>In Zeader, there are only two entities:</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2011/10/Model.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2011/10/Model-300x163.png" alt="" title="Model" width="300" height="163" class="alignnone size-medium wp-image-1543" /></a></p>

<p>In this example we want the Server entity to be updated whenever the read attribute on a child has changed.  To do that we are going to make a few enhancements to the Server entity subclass.</p>

<h3><code>-awakeFromInsert</code> and <code>-awakeFromFetch</code></h3>

<p>The first change we need to make is with the awake methods.  Whenever a Server entity is created or loaded we need to start listening for <code>NSManagedObjectContextObjectsDidChangeNotification</code> postings.</p>

<pre><code>- (void)awakeFromInsert
{
  [super awakeFromInsert];

  NSString *name = NSManagedObjectContextObjectsDidChangeNotification;
  NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  [center addObserver:self 
             selector:@selector(changes:) 
                 name:name 
               object:nil];
}

- (void)awakeFromFetch
{
  [super awakeFromFetch];

  NSString *name = NSManagedObjectContextObjectsDidChangeNotification;
  NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  [center addObserver:self 
             selector:@selector(changes:) 
                 name:name 
               object:nil];
}
</code></pre>

<h3><code>-willTurnInfoFault</code></h3>

<p>To be clean we need to stop listening whenever the Server is about to be removed from memory.  Since it is inappropriate to override the <code>-dealloc</code> method of a <code>NSManagedObject</code> we need to do so in the <code>-willTurnIntoFault</code> method.</p>

<pre><code>- (void)willTurnIntoFault
{
  [super willTurnIntoFault];
  NSString *name = NSManagedObjectContextObjectsDidChangeNotification;
  NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  [center removeObserver:self 
                    name:name 
                  object:nil];
}
</code></pre>

<p>This method of course, just like the two awake methods previously can be rolled up into just two lines.  They are broken apart here to make it easier to consume on the web.</p>

<h3><code>-changes:</code></h3>

<p>The last piece to the puzzle is the need to react to those changes as they are posted.</p>

<pre><code>- (void)changes:(NSNotification*)notification
{
  NSSet *objects = nil;
  NSMutableSet *combinedSet = nil;
  NSPredicate *predicate = nil;
  NSSet *unreadItems = nil;

  NSDictionary *userInfo = [notification userInfo];

  objects = [userInfo valueForKey:NSInsertedObjectsKey];
  combinedSet = [NSMutableSet setWithSet:objects];

  objects = [[notification userInfo] valueForKey:NSUpdatedObjectsKey];
  [combinedSet unionSet:objects];

  objects = [[notification userInfo] valueForKey:NSDeletedObjectsKey];
  [combinedSet unionSet:objects];

  predicate = [NSPredicate predicateWithFormat:@"entity.name == %@ &amp;&amp; server == %@", 
              @"FeedItem", self];
  [combinedSet filterUsingPredicate:predicate];

  if ([combinedSet count] == 0) {
    return;
  }

  predicate = [NSPredicate predicateWithFormat:@"read == NO"];
  unreadItems = [[self feedItems] filteredSetUsingPredicate:predicate];
  [self setUnreadCount:[unreadItems count]];
  DLog(@"server status changed %i", [unreadItems count]);
}
</code></pre>

<p>First, we do not really care whether the entities are inserted, deleted or updated.  We just need an answer to a simpler question: Are any of the entities that I care about in this change set?  Since our question is easier, we first can lump all of the changes into a single set.</p>

<p>Once we have all of the changes in a single set we then filter that set on the important question.  The predicate needs to be in a specific order; first we filter on the type of entity (<code>FeedItem</code>) we care about and then we filter on its relationship (is its <code>Server</code> me?).</p>

<p>This predicate reduces the <code>NSMutableSet</code> to only those <code>FeedItem</code> entities that are children of this instance of <code>Server</code>.  If that resulting <code>NSMutableSet</code> is zero then there are no relevant changes and we return; done.</p>

<p>If there are changes we want to update our <code>unreadCount</code>.  To do that we grab all of our <code>feedItems</code> and filter them with a simpler predicate of <code>@"read == NO"</code>.  The result of that filter can then be plugged into our <code>unreadCount</code>.</p>

<h2>Conclusion</h2>

<p>There are a few potential performance hot spots in this example.  However, the monitoring of children by the parent is always going to be a performance hotspot.  Therefore, great care should be given whenever to adding a watcher like this.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/10/14/parent-watching-its-child/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Core Data and the Undo Manager</title>
		<link>http://www.cimgf.com/2011/10/11/core-data-and-the-undo-manager/</link>
		<comments>http://www.cimgf.com/2011/10/11/core-data-and-the-undo-manager/#comments</comments>
		<pubDate>Tue, 11 Oct 2011 20:27:15 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Core Data]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1530</guid>
		<description><![CDATA[Note: This is a re-print from the Mac Developer Network. One of the nice things about developing software for OS X is all the “freebies” we get out of Cocoa. For example, when we are building a UI with text input we get undo support for free! How cool is that? Likewise, when we are [...]]]></description>
			<content:encoded><![CDATA[<p><em>Note: This is a re-print from the Mac Developer Network.</em></p>

<p>One of the nice things about developing software for OS X is all the “freebies” we get out of Cocoa.  For example, when we are building a UI with text input we get undo support for free!  How cool is that?</p>

<p>Likewise, when we are working with Core Data, it also has undo support built right in.  Every <code>NSManagedObjectContext</code> has a NSUndoManager that we can use.  However there are some situations where the default undo support is insufficient.</p>

<p>In this article we are going to walk through one such situation.
<span id="more-1530"></span></p>

<h2>Edit Window Undo</h2>

<p>There are situations where we want to group actions together so that from the user’s point of view they are an atomic operation.  For example, if we have a window with an edit sheet; once the edit sheet is closed we want to avoid walking through the individual edits that occurred while the sheet was present.</p>

<p>However, while the sheet is present, we do want to give the user the ability to undo each individual edit.  To perform this, we will be creating a commit group on the undo manager contained within the <code>NSManagedObjectContext</code> and we will use a separate Undo Manager that is responsible for the edit sheet.  We could use the undo manager within Core Data for both but I have found it to be cleaner to keep them separated in this situation.</p>

<h2>Building Our Application</h2>

<p><a href="http://www.cimgf.com/wp-content/uploads/2011/10/CDUM001.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2011/10/CDUM001-300x276.png" alt="" title="CDUM001" width="300" height="276" class="alignnone size-medium wp-image-1531" /></a></p>

<p>In this application the main window will present the user with a single table view which has two columns, a date and a name.  The table itself is non-editable but double clicking on a row will present a sheet for the user to edit the row.  In addition, clicking on the add button will present the same sheet but with a new entry.  The edit sheet contains three fields for data entry as shown.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2011/10/CDUM002.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2011/10/CDUM002-300x269.png" alt="" title="CDUM002" width="300" height="269" class="alignnone size-medium wp-image-1532" /></a></p>

<p>The data model for our project contains a single NSManagedObject named TestEntity with three properties: name, date and desc.  The model is shown in.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2011/10/CDUM003.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2011/10/CDUM003.png" alt="" title="CDUM003" width="185" height="139" class="alignnone size-full wp-image-1533" /></a></p>

<h2>Implementing the App Delegate</h2>

<p>Most of the <code>AppDelegate</code> is straight out of the Core Data Application template provided by Xcode.  However we are going to add a double click action to the table view as well as handling for the add and remove buttons.  To do this we need to add the table view as an outlet with the AppDelegate.  We also need to add the <code>NSArrayController</code> as an outlet.</p>

<pre><code>@interface AppDelegate : NSObject
{
  IBOutlet NSWindow *window;
  IBOutlet NSArrayController *arrayController;
  IBOutlet NSTableView *tableView;

  NSPersistentStoreCoordinator *persistentStoreCoordinator;
  NSManagedObjectModel *managedObjectModel;
  NSManagedObjectContext *managedObjectContext;
}

- (NSManagedObjectContext *)managedObjectContext;

- (IBAction)saveAction:(id)sender;
- (IBAction)addEntity:(id)sender;
- (IBAction)removeEntity:(id)sender;

@end
</code></pre>

<p>Once we have those bound in Interface Builder we can finish the configuration within the <code>-awakeFromNib:</code> method.</p>

<pre><code>- (void)awakefromNib
{
  [tableView setTarget:self];
  [tableView setDoubleAction:@selector(editEntry:)];
}
</code></pre>

<p>In the <code>-awakeFromNib:</code> we set ourselves as the target for the tableView and add the <code>-editEntry:</code> method as its double click action.  Now when a user double-clicks on a row our method will be called.</p>

<pre><code>- (void)editEntry:(id)sender
{
  id object = [[arrayController selectedObjects] lastObject];
  if (!object) return;
  SEL endSelector = @selector(editSheetDidEnd:returnCode:object:);
  [[[self managedObjectContext] undoManager] beginUndoGrouping];
  [[[self managedObjectContext] undoManager] setActionName:@"Undo Object Edit"];
  [EditWindowController editSheetForWindow:window
                                  delegate:self
                               endSelector:endSelector
                                    entity:object];
}
</code></pre>

<p>In the <code>-editEntry:</code> method we first get the object for the row that was clicked on.  We do a quick nil check and then hand the object off to our edit window controller.  As you can see we have a convenience method in our <code>EditWindowController</code> to make it easy to create one, pass off the object and display the sheet.  The method also accepts a delegate and a callback <code>@selector</code>.</p>

<p>You should pay particular attention to the line of code in the middle; the call to the NSManagedObjectContext&#8217;s NSUndoManager.  In that line we are starting a grouping before we present the sheet.  This guarantees that any changes made while the sheet is displayed will be considered &#8220;atomic&#8221; to the <code>NSUndoManager</code> contained within the <code>NSManagedObjectContext</code>.</p>

<h2>Implementing the EditWindowController</h2>

<p>The <code>EditWindowController</code> is a subclass of <code>NSWindowController</code> with a fairly simple header.</p>

<pre><code>#import &lt;Cocoa/Cocoa.h&gt;

@interface EditWindowController : NSWindowController 
{
  NSUndoManager *undoManager;
  NSManagedObject *testEntity;
  IBOutlet NSObjectController *entityController;
}

@property (assign) NSManagedObject *testEntity;

+ (void)editSheetForWindow:(id)window 
                  delegate:(id)delegate 
               endSelector:(SEL)selector 
                    entity:(NSManagedObject*)object;

- (IBAction)saveAction:(id)sender;
- (IBAction)cancelAction:(id)sender;

@end
</code></pre>

<p>We retain a reference to the <code>NSManagedObject</code> that gets passed in, an <code>NSObjectController</code> which is initialized within Interface Builder and a <code>NSUndoManager</code> which we will discuss below.  In addition to the iVars, we also have the accessor method that we used in the <code>AppDelegate</code> and two IBActions for the buttons on the edit sheet.</p>

<p>The interface builder xib only has a couple of objects:</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2011/10/CDUM004.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2011/10/CDUM004-300x180.png" alt="" title="CDUM004" width="300" height="180" class="alignnone size-medium wp-image-1534" /></a></p>

<p>The idea behind this design is that the window controller will receive an object which we will set into the <code>NSObjectController</code>.  The panel/sheet will then feed from this <code>NSObjectController</code> to display all of the editable fields.  Once the edit is complete the user will click either save or cancel which will close the sheet and cause the callback <code>@selector</code> to fire.</p>

<pre><code>+ (void)editSheetForWindow:(id)window 
                  delegate:(id)delegate 
               endSelector:(SEL)selector 
                    entity:(NSManagedObject*)object;
{
  EditWindowController *controller;
  controller = [[EditWindowController alloc] initWithWindowNibName:kNibName];

  [controller setTestEntity:object];

  [NSApp beginSheet:[controller window] 
     modalForWindow:window 
      modalDelegate:delegate 
     didEndSelector:selector 
        contextInfo:object];
}
</code></pre>

<p>Within our helper method we take advantage of the existing underlying API.  We first initialize an instance of the <code>EditWindowController</code> using the parent&#8217;s <code>-initWithWindowNibName:</code> which will load in the nib and attach all of the bindings for us.  Once that is complete we use the <code>-setTestEntity:</code> method to pass in the NSManagedObject which will populate all of the fields.  We then use the NSApplication call <code>+beginSheet: modalForWindow: modalDelegate: didEndSelector: contextInfo:</code> to present our associated window (a <code>NSPanel</code> really) as a sheet on top of the passed in window; which in this case happens to be the main window for our application.  The beauty of using this method to present the sheet is that we do not need to retain the delegate or the callback method, the existing structure handles it for us.</p>

<pre><code>- (void)saveAction:(id)sender;
{
  [[self window] orderOut:sender];
  [NSApp endSheet:[self window] returnCode:NSOKButton];
}

- (void)cancelAction:(id)sender;
{
  [[self window] orderOut:sender];
  [NSApp endSheet:[self window] returnCode:NSCancelButton];
}
</code></pre>

<p>We can further take advantage of the underlying structure in the save and cancel methods.  In each of these methods the only thing we need to do is call <code>-orderOut:</code> on our window and then call <code>-endSheet: returnCode:</code> on the NSApplication itself.  This will in turn call the delegate&#8217;s callback method with the appropriate return code.  Keeps our sheet very simple and clean.</p>

<p>The interesting part of this sheet is the undo manager.  In Interface Builder, I assigned the <code>EditWindowController</code> as the delegate to the window.  This means that the window looks to the <code>EditWindowController</code> to get a reference to the <code>NSUndoManager</code> that it should be using.  It is possible to use the <code>NSUndoManager</code> that is part of Core Data but we want to keep the edits made in this window local.  Therefore we are going to create a separate <code>NSUndoManager</code>.</p>

<pre><code>- (NSUndoManager*)windowWillReturnUndoManager:(NSWindow*)window
{
  if (!undoManager) {
    undoManager = [[NSUndoManager alloc] init];
  }
  return undoManager;
}
</code></pre>

<p>We create this <code>NSUndoManager</code> lazily.  We wait until it is requested the first time and then initialize it.</p>

<h2>Handling the Sheet Closing</h2>

<p>When the user is done with the sheet they will either hit save or cancel.  Both of those actions will cause the delegate&#8217;s callback method to be invoked.</p>

<pre><code>- (void)editSheetDidEnd:(id)sheet returnCode:(int)returnCode object:(id)object
{
  [[[self managedObjectContext] undoManager] endUndoGrouping];
  if (returnCode == NSOKButton) return;
  [[[self managedObjectContext] undoManager] undo];
}
</code></pre>

<p>In the callback method within the AppDelegate we first end the undo grouping that we started just before presenting the sheet.  We then check to see if the user pressed save or cancel.  If they pressed save we return and are done.  If they pressed cancel, however, we then request an undo on the <code>NSManagedObjectContext</code>&#8216;s <code>NSUndoManager</code>.  This will roll the <code>NSManagedObject</code> back to the state it was before we presented the sheet to the user.  Because we named this action the user will actually see it in the Edit menu.</p>

<h2>Handling Add Item</h2>

<p>We can reuse this edit sheet for when we are dealing with a new entity as well as editing an existing entity.  The only difference is in the <code>AppDelegate</code>&#8216;s <code>-addEntity:</code> method.</p>

<pre><code>- (void)addEntity:(id)sender;
{
  NSManagedObject *newObject;
  NSManagedObjectContext *moc = [self managedObjectContext];
  SEL endSelector = @selector(editSheetDidEnd:returnCode:object:);

  [[[self managedObjectContext] undoManager] beginUndoGrouping];
  [[[self managedObjectContext] undoManager] setActionName:@"Undo Object Add"];
  newObject = [NSEntityDescription insertNewObjectForEntityForName:@"TestEntity"
                                            inManagedObjectContext:moc];
  [EditWindowController editSheetForWindow:window
                                  delegate:self
                               endSelector:endSelector
                                    entity:newObject];
}
</code></pre>

<p>Instead of grabbing the selected object from the NSArrayController we construct a new one.  However we set the undoGrouping to begin <em>before</em> we create the object.  This allows us to include the creation of the <code>NSManagedObject</code> as part of the atomic undo.  If the user hits cancel on the sheet, the <code>NSManagedObject</code> will automatically be removed from the <code>NSManagedObjectContext</code> for us.</p>

<h2>Handling the Remove Item</h2>

<p>Like the Add menu item above, we can use the <code>NSUndoManager</code> to make the removing of objects easy for us as well.</p>

<pre><code>- (void)removeEntity:(id)sender;
{
  id object = [[arrayController selectedObjects] lastObject];
  if (!object) return;

  [[[self managedObjectContext] undoManager] beginUndoGrouping];
  [[[self managedObjectContext] undoManager] setActionName:@"Undo Object Remove"];
  [[self managedObjectContext] deleteObject:object];
  [[[self managedObjectContext] undoManager] endUndoGrouping];
}
</code></pre>

<p>Here we are grabbing the selected object from the table and if it exists we remove it from the <code>NSManagedObjectContext</code>.  However, we make sure to give the action a name.  Since it is a single action there is no need for a grouping but it is helpful, and improves the user experience to name the action so that the user understands exactly what they are undoing.</p>

<h2>Wrap-Up</h2>

<p>In this short article, we walked through how the <code>NSUndoManager</code> plays very nicely with Core Data and how we can use more than one <code>NSUndoManager</code> to keep the edits separate from each other instead of rolling them all into one undo stack and thereby avoiding all of the complication that entails.</p>

<p>It is possible to combine all of this work within one <code>NSUndoManager</code> but that causes the undo stack to be larger and more complicated unnecessarily.  There is no reason to retain the edits that were made within the edit sheet in the same <code>NSUndoManager</code> that handles the changes to the context.  By pulling these into their own <code>NSUndoManager</code> we can keep each separate function of the UI separate and easier to manage.</p>

<p><a href="http://cimgf.com/files/MultipleUndoManagers.zip">Download Sample Code</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/10/11/core-data-and-the-undo-manager/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Importing and displaying large data sets in Core Data</title>
		<link>http://www.cimgf.com/2011/08/22/importing-and-displaying-large-data-sets-in-core-data/</link>
		<comments>http://www.cimgf.com/2011/08/22/importing-and-displaying-large-data-sets-in-core-data/#comments</comments>
		<pubDate>Mon, 22 Aug 2011 19:48:18 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[NSOperation]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1525</guid>
		<description><![CDATA[Note: This is a re-print from the Mac Developer Network. I tend to frequent the StackOverflow website and watch for questions about Core Data. Generally if it is a question I can answer I will and if it is a question I can&#8217;t answer then I really dig in for a fun session of exploration [...]]]></description>
			<content:encoded><![CDATA[<p><em>Note: This is a re-print from the Mac Developer Network.</em></p>

<p>I tend to frequent the StackOverflow website and watch for questions about Core Data. Generally if it is a question I can answer I will and if it is a question I can&#8217;t answer then I really dig in for a fun session of exploration and attempt to find the answer.
<span id="more-1525"></span>
One question that I have been seeing with a tremendous amount of regularity is importing and displaying data on CocoaTouch devices.  Generally the question comes from one of a few problems:</p>

<ul>
<li>Trying to import a large amount of data causes the UI to hang.</li>
<li>Trying to save a large block of data causes the UI to hang.</li>
<li>Saving on exit causes the OS to kill the app.</li>
<li>Importing on launch causes the OS to kill the app.</li>
</ul>

<p>All of these &#8220;problems&#8221; are symptoms of the same two issues.</p>

<h2>Issues with large imports</h2>

<p>Importing a large amount of data, either from disk or from a network takes time and memory. If this is done on the main/UI thread then it becomes obvious to the user because the user interface is slow or unresponsive.  This leads to a poor experience for the user.</p>

<p>On the other side of this, once you get the data imported into Core Data then you need to save it.  If you are using a SQLite database then it can take a considerable amount of time.  If you are using a binary store then it will take even longer.  Again a poor user experience.</p>

<p>The answer to this problem involves multi-threading and breaking the job down into smaller pieces.</p>

<h2>Multi-threading</h2>

<p>There is a persistent rumor that you cannot use Core Data in a multi-threaded environment.  This is patently false.  Core Data works very well in a multi-threaded environment but you need to play by the rules:</p>

<ul>
<li>One <code>NSManagedObjectContext</code> per thread.</li>
<li><code>NSManagedObject</code> instances cannot pass between threads.</li>
</ul>

<p>As long as we follow those two rules, we can use Core Data in a multi-threaded environment.</p>

<h2>Breaking It Apart</h2>

<p>The biggest issue with imports is that they are generally huge.  That is going to kill performance even if it is done on a background thread.  This is especially apparent on Cocoa Touch right now because of the single core devices that it runs on.  Therefore, the first thing we <strong>must</strong> do is break that import apart.</p>

<p>I recommend splitting the incoming data (XML/JSON/whatever) into multiple files that you save on disk.  Number these files sequentially.  When the data is fully transferred from the network then start processing them.  In addition, keep track of which file you are currently working on.  When that file is complete and saved, move on to the next file and update the marker.  You can store the marker either in the <code>NSUserDefaults</code> or inside of the metadata of the <code>NSPersistentStore</code> itself.  In either case the idea is that if the user quits in the middle of the import you do not need to start over at zero.  You pick up right where you left off.</p>

<h2>Code Example</h2>

<p>In the attached sample project I have created a very trivial example of an import occurring on a background thread.  If you were actually pulling in data from the net as I described above, you would actually have numerous <code>NSOperation</code> objects that are queued up to run.  However in this example we have a single <code>NSOperation</code> that sleeps periodically.</p>

<p>The heart of this example is the periodic saves.  We want to save frequently enough that each save is very quick.  In addition, when the save occurs, we want to update the main <code>NSManagedObjectContext</code> so that it can refresh which will in turn update the <code>NSFetchedResultsController</code> which will in turn update the UI.  Crazy enough? Let&#8217;s dive in.</p>

<h3>RootViewController <code>-startImport:</code></h3>

<p>If you are familiar with Core Data on Cocoa Touch then most of this class will be very familiar.  Other than code clean up it is straight from the current Xcode template.  Having said that, there are a couple of differences.</p>

<p>The <code>-startImport:</code> method is fired from tapping the start button in the <code>NSNavigationItem</code> shown at the top of the screen.  This method will create the <code>NSOperationQueue</code> if it has not already been created and then it will create our <code>NSOperation</code> which will do the simulated work in the background.</p>

<pre><code>- (void)startImport:(id)sender
{
  [[[self navigationItem] rightBarButtonItem] setEnabled:NO];
  [[[self navigationItem] leftBarButtonItem] setEnabled:NO];

  if (![self operationQueue]) {
    operationQueue = [[NSOperationQueue alloc] init];
  }

  ZSImportOperation *op = [[ZSImportOperation alloc] init];
  [op setPersistentStoreCoordinator:[[self managedObjectContext] persistentStoreCoordinator]];
  [op setRunSpeed:0.25];
  [op setEntriesToCreate:1000];
  [op setSaveFrequency:10];

  [operationQueue addOperation:op];
  [op release], op = nil;
}
</code></pre>

<p>Note that we have several parameters that we are setting on the <code>ZSImportOperation</code> instance.  This dependency injection allows us to pass along the <code>NSPersistentStoreCoordinator</code> to the operation so that it can construct its own <code>NSManagedObjectContext</code> once it starts.  We cannot create the <code>NSManagedObjectContext</code> ourselves and pass it along because that will break the thread barrier and the results are undetermined (<em>i.e.</em> very bad).</p>

<p>We also tell it how many objects to create, how long to pause between each creation and how often to save (<em>i.e.</em> switch files).  Once everything is configured we pass it along to the <code>NSOperationQueue</code> and it starts.</p>

<h3>RootViewController <code>-contextChanged:</code></h3>

<p>This is where the magic happens as they say.  This method is called whenever any <code>NSManagedObjectContext</code> in the entire application saves.  We configured this in the <code>-viewDidLoad</code> method by calling:</p>

<pre><code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextChanged:) name:NSManagedObjectContextDidSaveNotification object:nil];
</code></pre>

<p>When this method is fired we know that the data has changed somehow, somewhere.  So we need to narrow it down and confirm it is a data change we care about.</p>

<pre><code>- (void)contextChanged:(NSNotification*)notification
{
  if ([notification object] == [self managedObjectContext]) return;

  if (![NSThread isMainThread]) {
    [self performSelectorOnMainThread:@selector(contextChanged:) withObject:notification waitUntilDone:YES];
    return;
  }

  [[self managedObjectContext] mergeChangesFromContextDidSaveNotification:notification];
}
</code></pre>

<p>Fortunately we are not in a document based application so we really just need to check that the object pointer in the notification is not pointing to our <code>NSManagedObjectContext</code>.  If it is, we bail.</p>

<p>We also need to make sure that all work done is on the main thread.  Now I could just perform the last line of code in the <code>-performSelectorOnMainThread:withObject:waitUntilDone:</code> method and in this case I probably should.  However this is another option in case the code you need to perform on the main thread is complex and you don&#8217;t want to write 12 <code>-performSelectorOnMainThread:withObject:waitUntilDone:</code> calls or write yet another method to be called.  In this example, if we are not on the main thread we recursively call ourselves from the main thread and wait.  This will guarantee that what happens next will always be on the main thread.</p>

<p>The final line is what triggers everything.  This line of code is telling the main <code>NSManagedObjectContext</code> that the underlying data has changed and that it needs to update itself.  This will in turn cause the <code>NSFetchedResultsController</code> to get woken up which finally updates the UI.</p>

<h3>ZSImportOperation <code>-main</code></h3>

<p>This <code>NSOperation</code> subclass is the most trivial example I could come up with.</p>

<pre><code>- (void)main
{
  ZAssert([self persistentStoreCoordinator], @"PSC is nil");
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

  [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSRunLoopCommonModes];

  NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
  [moc setPersistentStoreCoordinator:[self persistentStoreCoordinator]];

  NSError *error = nil;

  for (NSInteger index = 0; index &lt; [self entriesToCreate]; ++index) {
    id object = [NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:moc];
    [object setValue:[NSString stringWithFormat:@"User %i", index] forKey:@"name"];
    [object setValue:[NSNumber numberWithInteger:(arc4random() % 99)] forKey:@"age"];

    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:[self runSpeed]]];

    if (index % [self saveFrequency] != 0) continue;

    ZAssert([moc save:&amp;error], @"Error saving context on operation: %@\n%@", [error localizedDescription], [error userInfo]);

    DLog(@"saving background context");
    [moc reset];
    [pool release];
    pool = [[NSAutoreleasePool alloc] init];
  }

  ZAssert([moc save:&amp;error], @"Error saving context on operation: %@\n%@", [error localizedDescription], [error userInfo]);

  [moc release], moc = nil;

  [[NSNotificationCenter defaultCenter] postNotificationName:kImportRoutineComplete object:self];

  [pool release], pool = nil;
}
</code></pre>

<p>It starts with creating a separate <code>NSManagedObjectContext</code> as per the rules.  We then add an empty port so that we can lazily sleep this thread.  From there we start looping based on the set <code>entriesToCreate</code> value.</p>

<p>Inside of the loop we create a new <code>NSManagedObject</code> and give it some random values.  We then sleep based on the <code>runSpeed</code> value.  From there we check to see if it is time to save and if not we move on to the next iteration of the loop.</p>

<p>If it is time to save we then perform a <code>-save:</code> on the <code>NSManagedObjectContext</code> instance wrapped inside of a <code>ZAssert</code>.  The <code>ZAssert</code> allows us to do a conditional check on the results and then spit out either a <code>NSAssert</code> or <code>NSLog</code> depending on whether we are compiling in debug (which would throw an assertion) or production (which will spit out an NSLog).</p>

<p>Once the save is complete we reset the <code>NSManagedObjectContext</code> instance to release the memory it is holding onto and then drain the <code>NSAutoreleasePool</code>.</p>

<p>Once all of the requested objects have been created we perform one final save of the <code>NSManagedObjectContext</code> and drain the <code>NSAutoreleasePool</code> one final time.  We also send out a <code>NSNotification</code> just so that we can update the UI and re-enable the buttons.</p>

<h2>Wrap Up</h2>

<p>If you run the sample application you will notice a few things:</p>

<ul>
<li>The app runs smoothly even while processing data.</li>
<li>The app does not crash on launch due to the OS killing it.</li>
<li>THe app does not crash on exit because the save takes too long.</li>
</ul>

<p>Naturally this is more work for us as the developers but the end result is an application that can handle any amount of data without fear of freezing the UI or having the OS kill our application.</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2011/08/PerformantImport.zip'>You can download the sample project here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/08/22/importing-and-displaying-large-data-sets-in-core-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Conference: MacTech (Los Angeles, CA, USA)</title>
		<link>http://www.cimgf.com/2011/08/12/conference-mactech-los-angeles-ca-usa/</link>
		<comments>http://www.cimgf.com/2011/08/12/conference-mactech-los-angeles-ca-usa/#comments</comments>
		<pubDate>Fri, 12 Aug 2011 17:26:32 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Announcement]]></category>
		<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1516</guid>
		<description><![CDATA[When: November 2-4, 2011 Where: Los Angeles, CA Schedule and Additional Information The speaker line up for MacTech this year is amazing. I am quite honored to be sharing the stage with such a group of people. What is MacTech Conference? MacTech Conference is a 3-day, immersive, technical conference specifically designed for Apple developers, IT [...]]]></description>
			<content:encoded><![CDATA[<p>When: November 2-4, 2011<br />
Where: Los Angeles, CA</p>

<p><a href="http://www.mactech.com/conference/about">Schedule and Additional Information</a></p>

<p>The speaker line up for MacTech this year is amazing. I am quite honored to be sharing the stage with such a group of people.</p>

<h2>What is MacTech Conference?</h2>

<p>MacTech Conference is a 3-day, immersive, technical conference specifically designed for Apple developers, IT Pros, and Enterprise. &#8220;The whole idea of MacTech Conference is to allow members of the Apple community to meet and exchange ideas,&#8221; said Edward Marczak, Conference Chair and Executive Editor of MacTech Magazine. &#8220;This will be spurred on by presentations from some of the best and well-known experts in the community.&#8221;</p>

<p>MacTech Conference will have two separate tracks: one focused on programming / development, and the other on IT/Enterprise. Sessions will focus on both desktop and mobile, with appropriate levels of attention paid to the Mac, iPhone, iPad and iPod.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/08/12/conference-mactech-los-angeles-ca-usa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Transient Entities and Core Data</title>
		<link>http://www.cimgf.com/2011/08/08/transient-entities-and-core-data/</link>
		<comments>http://www.cimgf.com/2011/08/08/transient-entities-and-core-data/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 23:24:04 +0000</pubDate>
		<dc:creator>Saul Mora</dc:creator>
				<category><![CDATA[Core Data]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1493</guid>
		<description><![CDATA[Core Data has many features, one of which is the Transient attribute. This type of attribute on a Core Data entity is part of a data model, but is not persisted in your Core Data persistent store. If you open up the raw SQLite store file and peek at the schema, you will not find [...]]]></description>
			<content:encoded><![CDATA[<p>Core Data has many features, one of which is the Transient attribute. This type of attribute on a Core Data entity is part of a data model, but is not persisted in your Core Data persistent store. If you open up the raw SQLite store file and peek at the schema, you will not find any transient attributes. These transient attributes are still handy despite no data being persisted to the data store. One useful scenario is when a value is calculated based on other attributes. This calculation can be performed in an entity&#8217;s awakeFromFetch method, and stored at run time in this transient attribute.</p>

<p>One scenario I&#8217;ve been asked about on more than one occasion recently is that of temporary, or transient entities. It seems that more and more developers have a need for temporary, or transient instances of entities in your Mac or iOS apps. Having temporary object instances can be useful and necessary in certain situations. Unfortunately, Transient Entities do not technically exist within the Core Data framework, however there are simple solutions to add temporary, un-persisted, data within the context of Core Data. Let&#8217;s go over some methods to effectively use the concept of Transient, or more appropriately Temporary Entities in Core Data without direct built-in support.</p>

<p><span id="more-1493"></span></p>

<h2>Why even put them in Core Data in the first place?</h2>

<p>This should be the first qustion you ask when you&#8217;re talking about going down the path of doing something with Core Data that it doesn&#8217;t already do for you. So, why not just use Plain Old Objective-C Objects &#8230; POOCOs anyone? There are a couple scenarios in which you would want even your temporary objects to be NSManagedObjects. The main situation is where you actually do persist the instance to the persistent store. Another case may be that your data objects are easily defined, modeled and imported through the Core Data toolset. That is, you have an entity defined and related to other entities in your object graph in your Model, and the import code is shared or related. In this case, it may be more maintainable to just let that all coexist. The most common reason is that you want to have a temporary object with the option to cancel and destroy it at any time. This is common in a &#8220;New Document&#8221; situtation where the user wants to enter new data, but decides to cancel half way in, and discard what&#8217;s already been entered.</p>

<p>Whatever the reason, it should be through a rigorous process that you have ultimately decided that your objects are better off as NSManagedObject instances and not just plain old Objective C objects with references to NSManagedObjects. In most cases you will be better off not even dealing with the complexity of temporary NSManagedObjects in the first place.</p>

<p>That being said, since you&#8217;ve come this far, it seems likely that maybe you really do have a good reason to have a temporary object instance as a Core Data object. Great, let&#8217;s go over three common, and easy to implement, solutions with code to show how to handle this as simply as possible. Also, we&#8217;ll go over the pros and cons of each approach as there are certainly tradeoffs which you must evaluate in order to choose the correct solution for your problem.</p>

<p>The code samples shown here will be using the helpers found in <a href="http://github.com/magicalpanda/MagicalRecord">Magical Record</a>, available on github.</p>

<h2>Scratch Managed Object Context</h2>

<p>Perhaps the simplest scenario in creating temporary NSManagedObjects is to create them in a temporary NSManagedObjectContext. Apple&#8217;s documentation commonly refers to the NSManagedObjectContext as a &#8216;scratch pad&#8217; or &#8216;working area&#8217; for changes to NSManagedObjects. When you create any NSManagedObject in a Managed Object Context, it is not perisisted to the store util you call <strong>save: </strong>on that context. By not calling <strong>save:</strong> on a second scratch context, any changes made will dissappear when the context, and the managed objects it contains, is dealloc&#8217;ed. Let&#8217;s take a look at implementing this example in code:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> MyViewController <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>scratchContext;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> MyViewController
@synthensize scratchContext <span style="color: #002200;">=</span> scratchContext_;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewDidLoad
<span style="color: #002200;">&#123;</span>
  self.scratchContext <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSManagedObjectContext</span> context<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
...
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>importData
<span style="color: #002200;">&#123;</span>
  MyEntity <span style="color: #002200;">*</span>instance <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>MyEntity createInContext<span style="color: #002200;">:</span>self.scratchContext<span style="color: #002200;">&#93;</span>;
  <span style="color: #11740a; font-style: italic;">// data initialization code</span>
  <span style="color: #11740a; font-style: italic;">// don't call save:</span>
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSManagedObjectContext</span> defaultContext<span style="color: #002200;">&#93;</span> save<span style="color: #002200;">&#93;</span>; <span style="color: #11740a; font-style: italic;">// won't save anything in the scratch context</span>
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></div></div>


<p>In this first example, we have two NSManagedObjectContext objects, the first is created for you when you use one of <a href="http://github.com/magicalpanda/MagicalRecord">MagicalRecord&#8217;s</a> setup methods. As described <a href="http://www.cimgf.com/2011/03/13/super-happy-easy-fetching-in-core-data/">in a previous post</a>, this first context is set as the default context for all Core Data operations. However, in this scenario, we want to create a second context that uses the same persistent store. Using MagicalRecord, this is as simple as using the <strong>context</strong> method. This will create a new NSManagedObjectContext instance, and initialize it with the default NSPersistentStoreCoordinator. This is all that&#8217;s necessary to create a usable scratch context. Now, instead of creating entities in the default context, perform them in this scratch context. This is what&#8217;s happening in the importData method. By creating a new entity in the scratch context, we&#8217;re making a temporary object that potentially can be thrown away when we&#8217;re done with the view controller.</p>

<h2>In Memory SQLite Persistent Store</h2>

<p>One of the useful features of SQLite is that it can also persist simply in memory, or system RAM, only. This feature translates to Core Data persistent stores quite nicely as it&#8217;s a simple configutation change to the <strong>addPersistentStore: </strong>call when setting up your NSPersistentStoreCoordinator instance.  To simplify things, while adding this option, we&#8217;re going to go over adding an in-memory SQLite store to the same default NSPersistentStoreCoordinator.  This route may not be the common route in iOS apps, but Core Data is set up to handle the mapping and complexity of multiple stores for you, so it makes sense to use that functionality for this solution to try to keep the code as simple as possible.  Let&#8217;s take a look at some code:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> SampleAppDelegate <span style="color: #002200;">&amp;</span>lt;UIApplicationDelegate<span style="color: #002200;">&amp;</span>gt;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSPersistentStore</span> <span style="color: #002200;">*</span>inMemoryStore;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSPersistentStore</span> <span style="color: #002200;">*</span>fileBasedStore;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> SampleAppDelegate
<span style="color: #a61390;">@synthesize</span> inMemoryStore <span style="color: #002200;">=</span> inMemoryStore_;
<span style="color: #a61390;">@synthesize</span> fileBasedStore <span style="color: #002200;">=</span> fileBasedStore_;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>awakeFromNib
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>MagicalRecordHelpers setupDefaultCoreDataStack<span style="color: #002200;">&#93;</span>;
    self.fileBasedStore <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSPersistenStoreCoordinator defaultCoordinator<span style="color: #002200;">&#93;</span> persistentStores<span style="color: #002200;">&#93;</span> objectAtIndex<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>;
    self.inMemoryStore <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSPersistentStoreCoordinator</span> defaultCoordinator<span style="color: #002200;">&#93;</span> addInMemoryStore<span style="color: #002200;">&#93;</span>;  <span style="color: #11740a; font-style: italic;">//configure in memory store&lt;br /&gt;</span>
<span style="color: #002200;">&#125;</span>
...
<span style="color: #a61390;">@implementation</span> MyViewController
<span style="color: #11740a; font-style: italic;">//assign new object to in memory persistent store</span>
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>MyEntity<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>createTemporaryEntity
<span style="color: #002200;">&#123;</span>
    MyEntity <span style="color: #002200;">*</span>newInstance <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>MyEntity createEntity<span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>context <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSManagedObjectContext</span> defaultContext<span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSPersistentStore</span> <span style="color: #002200;">*</span>inMemoryStore <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#40;</span>SampleAppDelegate <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIApplication sharedApplication<span style="color: #002200;">&#93;</span> delegate<span style="color: #002200;">&#93;</span> inMemoryStore<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>context assignObject<span style="color: #002200;">:</span>newInstance toPersistentStore<span style="color: #002200;">:</span>inMemoryStore<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">return</span> newInstance;
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></div></div>


<p>We&#8217;ve again use the <a href="http://github.com/magicalpanda/MagicalRecord">MagicalRecord</a> helpers in this second example to create an in-memory SQLite store on the default NSPersistentStoreCoordinator. Notice that we also must keep a reference to it in our app delegate. The reason for this reference is easy to understand once we get to creating temporary object instances in the createTemporaryEntity method on MyViewController. Creating an entity is as straight forward as always, however, we must then assign this new entity to the in-memory store using our saved reference. We must also assign our non-temporary objects to the <em>fileBasedStore</em> as well.</p>

<p>There is one rather large caveat to this solution&#8211;on iOS devices in particular. There is a finite limit to what you can store in memory during the lifetime of an app. Going over this limit can be grounds for termination by the system watchdog process. If you implement this solution and find that you are constantly hitting a memory limit in your app due to the temporary in memory store, a simple variant to this solution is to make this a regular disk based SQLite store, but make it a secondary store, one that can easily be deleted by some clean up code later on. By persisting the store to disk, you don&#8217;t have the same constant memory pressure, and you also still have a secondary store which only contains temporary instances of your objects.</p>

<h2>Mark Entities for deletion, and delete later</h2>

<p>In our third scenario, the Core Data stack remains the same as in our original simple Core Data stack setup. However, this situation is helpful when objects are being used by the UI. In some cases, references to managed objects in the UI may have a reason to delay the release of these objects. In order to avoid crashes due to deleting the persistence information out from under the object, we can simply say that entity should be deleted later. <a href="http://github.com/magicalpanda/MagicalRecord">MagicalRecord</a> provides a truncateAll (and the truncateAllInContext: variant) to remove all the instances of a particular type from the store. However, in this case, we need to have a more specific filter on a flag on the entity.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>MRCoreDataAction saveDataWithBlock<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>localContext<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSPredicate</span> <span style="color: #002200;">*</span>itemsToDeleteSearch <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSPredicate</span> predicateWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;shouldBeDeleted = YES&quot;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>itemsToDelete <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>SampleEntity findAllWithPredicate<span style="color: #002200;">:</span>itemsToDeleteSearch<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObject</span> <span style="color: #002200;">*</span>entity <span style="color: #a61390;">in</span> itemsToDelete<span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>entity deleteInContext<span style="color: #002200;">:</span>localContext<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>In the case where the shouldBeDeleted flag is a transient attribute, using an NSPredicate search against the store will not work as this attribute is not even created in the SQLite schema for that entity. A variant on this solution is to hang on to those deleted references in an NSMutableArray (or NSMutableSet) and iterate on that collection at the appropriate time. However, this variant may backfire in the event of a crash or a forced termination. That is, in either of those scenarios, your collection of instances to delete will no longer be in memory.</p>

<p>On iOS 4 and above, applications can enter the &#8220;background&#8221;. This is a perfect time to perform this delayed purge as it can be done without the user really noticing any UI jerkiness caused by merges. Heck, if you make other apps slow down, the user may just blame that one! (Don&#8217;t do this…be a good app citizen).</p>

<h2>Conclusion</h2>

<p>I&#8217;ve just described three ways to deal with temporary Core Data objects. These are by no means the only ways to handle transient entities, however, these are relatively simple concepts. The code for each of these examples is also simple enough to retrofit into existing application code. If you have other solutions relating to the idea of temporary storage, I&#8217;d be happy to hear about them in the comments below!</p>

<p> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/08/08/transient-entities-and-core-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Conference: 360 iDev (Denver, CO, USA)</title>
		<link>http://www.cimgf.com/2011/08/01/conference-360-idev/</link>
		<comments>http://www.cimgf.com/2011/08/01/conference-360-idev/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 17:25:47 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Announcement]]></category>
		<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1482</guid>
		<description><![CDATA[When: September 11-14, 2011 Where: Denver, Colorado Schedule and Additional Information I am very pleased to announce that I will be speaking at this year&#8217;s 360 iDev conference in Denver, Colorado. Previously it was a foregone conclusion that I would be attending this conference since it was so close to my home. However, now that [...]]]></description>
			<content:encoded><![CDATA[<p>When: September 11-14, 2011<br />
Where: Denver, Colorado</p>

<p><a href="http://360idev.com/">Schedule and Additional Information</a></p>

<p>I am very pleased to announce that I will be speaking at this year&#8217;s 360 iDev conference in Denver, Colorado. Previously it was a foregone conclusion that I would be attending this conference since it was so close to my home. However, now that I am living in California, that is no longer the case.</p>

<p>However, I am happy to say that I will be attending this year despite a change in my home address. The speaker line up at 360 iDev keeps getting better each year and I am happy to be a part of this <a href="http://360idev.com/speakers">great lineup</a>.</p>

<p>If you are on the fence about going to this conference then please take my advice; GO.</p>

<p>Not only is the speaker line up great but Denver has a great walking downtown and the after session events should be just as entertaining as the speakers themselves.</p>

<p>I look forward to seeing you there.</p>

<p><img src="http://www.cimgf.com/wp-content/uploads/2011/08/Signoff1.png"/></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/08/01/conference-360-idev/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Conference: Update 2011 (Brighton, UK)</title>
		<link>http://www.cimgf.com/2011/07/28/conference-update-2011-brighton-uk/</link>
		<comments>http://www.cimgf.com/2011/07/28/conference-update-2011-brighton-uk/#comments</comments>
		<pubDate>Thu, 28 Jul 2011 21:20:28 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Announcement]]></category>
		<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1473</guid>
		<description><![CDATA[When: September 5-7, 2011 Where: Brighton, UK Schedule and Additional Information I am very pleased to announce that I will be speaking in Brighton at the Update conference starting on September 5, 2011. The Update conference is a bit different than the normal &#8220;developer&#8221; conference that I attend and speak at. Instead of just or [...]]]></description>
			<content:encoded><![CDATA[<p>When: September 5-7, 2011<br />
Where: Brighton, UK</p>

<p><a href="http://updateconf.com/">Schedule and Additional Information</a></p>

<p>I am very pleased to announce that I will be speaking in Brighton at the <a href="http://updateconf.com/">Update conference</a> starting on September 5, 2011.  The Update conference is a bit different than the normal &#8220;developer&#8221; conference that I attend and speak at.  Instead of just or primarily focusing on the developer; a great deal of focus is put upon the user and the user experience. If you have been in attendance for any of Aral Balkan&#8217;s talks then you know very well what his focus is.</p>

<p>In addition to speaking at the conference I will be giving <strong>two</strong> one day workshops on Core Data.  The first workshop will be an introduction to Core Data.  I hesitate to call this a beginner workshop because <em>you</em>, the attendees, will be directing the workshop.  If everyone wants to start at step one then we will.  However throughout the day you will be setting the pace of what we learn and discuss. This format has worked very well in the past and the last time we did a workshop like this the day ended with some pretty advanced discussions.</p>

<p>The second session is labelled advanced and will be starting off with the assuming that we all know and understand the principals behind Core Data.  In this session we will deep dive into some of the more complex areas of Core Data.  Again, I have a list of topics but you, the attendees, drive the session.  Therefore it is intentionally open ended so that you can come with your questions and problems and we can discuss them together.  I plan on wrapping up the second workshop with some real world examples of edge cases and situations I have run into and how they were solved.</p>

<p>I invite you to join me in Brighton this September to attend <a href="http://updateconf.com/">Update 2011</a>.  I expect it to be a great time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/07/28/conference-update-2011-brighton-uk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why So Serious?</title>
		<link>http://www.cimgf.com/2011/06/03/why-so-serious/</link>
		<comments>http://www.cimgf.com/2011/06/03/why-so-serious/#comments</comments>
		<pubDate>Fri, 03 Jun 2011 22:52:00 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Rants]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1464</guid>
		<description><![CDATA[This is a post that has been sitting in the back of my mind for many months now. I originally conceived of writing this back in February of 2011 but decided that the time was not right for it and waited. Had I written it back then I suspect the text would have been quite [...]]]></description>
			<content:encoded><![CDATA[<p>This is a post that has been sitting in the back of my mind for many months now. I originally conceived of writing this back in February of 2011 but decided that the time was not right for it and waited.  Had I written it back then I suspect the text would have been quite a bit different.</p>

<p>I was part of the original development team that wrote &#8220;The Daily&#8221; for News Corp.</p>

<p>When &#8220;The Daily&#8221; was released, we expected some issues with it. Every developer should expect issues with a 1.0 release. We knew that it was written under a tight deadline and that there were most certainly sharp edges that we had not identified. The application was about as well received as we could expect from the user base. Some people do not like Rupert Murdoch. Some people do not like his teams slant on the news. That was expected. He is good at polarizing his readership.</p>

<p>The response we got from the developer community was a complete surprise.</p>

<h2>Back In The Day</h2>

<p>One of the things that originally attracted me to being a Mac/Cocoa developer was the community. I remember, fondly, watching two direct competitors sitting across a table from one another trading code solutions. Both knew that the other person was going to add it to their code base and they shared that information anyway. Both developers knew that it was the other developer that was driving them to make a better product. There can be no first place without a second place. Having a close competitor helps drive us forward.</p>

<p>Likewise, going to a CocoaHeads meeting you would see senior developers, developers who have been doing this for decades, sitting next to developers who are just now wrapping their heads around retain/release. They weren&#8217;t pained but instead looking upon the younger developer with the fondness of remembering what it was like when they started. Perhaps a bit of envy of all the exciting things this new young developer is about to learn.</p>

<h2>Introducing The iPhone</h2>

<p>When the iPhone was introduced we were all very excited to start working with it. Cocoa on a mobile platform! We could not wait to get our hands on it. The community embraced it immediately.</p>

<p>At first you had to hack your phone to write code for it but we quickly got an SDK. The community consumed that SDK with a hunger. The forums were active, the boards were active, the blogs were hot. Everyone wanted to share the new cool thing they learned or share the pain they just went through so that, hopefully, no one else had to go through that pain. The community was alive and prosperous.</p>

<p>I do remember many conversations about what would happen to the community with this sudden influx of developers. Many conversations started over what to do about these developers invading our platform. When I was involved in those discussions my response was always the same; we would welcome them to the community and teach them how we work. We would show them how great it is over here and that we share our toys. We would welcome them knowing that they would become part of us; not the other way around.</p>

<p>For the most part that is what happened. A large portion of these developers joined us. They shared; many new blogs started up, new books were written and our NSCoder nights and CocoaHeads meetings grew. The community became stronger with this influx of new developers.</p>

<h2>A Disturbing Trend</h2>

<p>More recently, perhaps within the last year, there has been a disturbing trend in the community. Surprisingly, sadly, this trend has not come from the new developers but from some of the older grey beards. There has been a trend to &#8220;piss on&#8221; things written by other developers. A new app comes out, good or bad, and the claws come out. People are quick to blast it; the more press it gets, the more it gets blasted.</p>

<p>A new photo sharing idea that got a lot of VC money? <em>Blast it!</em></p>

<p>A new game concept? <em>Kill it!</em></p>

<p>An old idea rehashed in a new way? <em>Destroy it! Burn them!</em></p>

<p>He got more press than me? <em>He must die in a fire!</em></p>

<p>I would almost expect this from new developers who just joined the community. However it is not the new members of this community that are all aflame. Most likely they are looking at these ideas and seeing how they can apply them or if there is anything to learn from them.</p>

<p>Sadly though, it is the older, established, members of the community that are turning so hostile. Gone is the sharing and the live/let live attitude that once made this community so great. Quite a few members are just full of piss and vinegar.</p>

<p>You can say what you want about me. I do not hold myself above others and know that my code sucks more often than not. I tend to share that opinion of my code often. I do not share what I have learned to gain glory but to just enjoy the act of sharing. Sharing makes me feel good.</p>

<p>What saddens me is this new desire to attack things that are either new or just in the media. Does the application suck? Maybe. But to curse the developers who wrote it? Not cool.</p>

<p>We as developer must remember that we are <strong>not</strong> the target for 99% of the software that is written. We are not the final judge on what will or will not work. If anything, we are the last people that should have an opinion on what is good or bad. We should be the ones that step back and watch what the &#8220;normals&#8221; do with it. <strong>They</strong> determine the success or failure; not <em>us</em>.</p>

<h2>Some Thoughts From The Trenches</h2>

<p>Not everyone who reads this blog is an independent developer. Not everyone who reads this blog writes code to fit someone else&#8217;s goals so I would like to share a few points from someone who is an independent developer and writes code to meet the expectations from others.</p>

<h3>Deadlines are a bitch</h3>

<p>Rarely do I have the opportunity to set my own deadlines. Companies who hire development shops almost always have a deadline in mind before the first line of code is ever written. More often than not, they have a deadline in mind before they have all of the requirements defined.</p>

<p>We, as developers, do not get to move those deadlines without massive and dire consequences. Usually our only opportunity to move them is at the beginning and then by saying &#8220;No, Thank You&#8221; to the project. Moving a deadline mid project usually has financial consequences.</p>

<h3>Non-Developers Think This Is Easy</h3>

<p>Non-developers see that one new feature as trivial. They see that crash as obvious and do not understand what the hell is taking so long. Business people are non-developers. The people who sign checks are business people.</p>

<p>To go along with my point about deadlines, getting paid involves meeting the requirements of the project within the deadline. These are almost always at odds with each other. The requirements are far greater than can be fit within the deadline. The response from the business team is &#8220;add more people, make it happen&#8221;. We as developers know that adding more people will actually slow things down.</p>

<h3>The First 90% Is Easy</h3>

<p>Developers frequently look at a problem and in their first blush say &#8220;oh I see how that works, that is <em>simple</em>&#8220;. That is a trap my friends. Everything looks easy at first. My favorite recent example is the carousel of The Daily. It is trivial right? No, there are a huge number of dependencies and features and bells and whistle and edge cases that all work their way into that piece of the application. The core of moving images around on the screen is trivial. Anyone can do it in a couple of hours. However to complete all of the requirements? Months of work. Personally I am still not completely happy with it. Maybe with 6 more months of polish it will get to where I would like to see it.</p>

<p>Never underestimate the requirements that go into a piece of functionality. Don&#8217;t assume that the developers are incompetent if it doesn&#8217;t work or perform the way you expect it to. Chances are that there are requirements that you as a user are unaware of.</p>

<h3>Software Development Is Not The Only Cost</h3>

<p>This is my one hostile point in this post. Whoever thought the iOS developers got paid $30 Million on &#8220;The Daily&#8221; is a moron.</p>

<p>&#8220;The Daily&#8221; is a <strong>lot</strong> bigger than just writing iOS code. There is a huge editorial staff, there is a server team, there is office space, hardware, travel, the list goes on and on. The actual iOS code was a small fraction of the huge effort that was put into creating a digital only daily newspaper; the first of its kind by the way.</p>

<h3>Doing Something First Sucks</h3>

<p>Unless you are trying to get into some record book, the person who does something first is rarely remembered. He who does it best is often remembered fondly. When you are the first to do something you rarely are the best at it. This is just a simple fact of life. When you are the first to do something you are making shit up as you go along. You are guessing. You have no clue what is going to happen when you release. The first MP3 player? Shit. First Tablet? Horrible.</p>

<p>Being first means that you are going to be superseded. Either by improving on your design or by being replaced by another team that took your idea and ran with it. The iPod blew away the first MP3 player. The iPad blew away the first Tablet. I look forward to seeing who becomes the greatest digital only daily newspaper on a tablet. Maybe that will be The Daily via iteration or maybe it will be someone else.</p>

<h2>Conclusion</h2>

<p>&#8220;Be excellent to each other&#8221; &#8212; Bill &amp; Ted&#8217;s Excellent Adventure</p>

<p>This should be the guiding principal of the Cocoa Developer Community in my not-so-humble opinion. It is one of the things that make it great. New people are welcomed and the older members are honored.</p>

<p>There is no reason to hate other development efforts. It does not matter if that developer is better or worse than you. It does not matter what that developer wrote. There is plenty of room for all of us.</p>

<p>Be excited by his or her success. His or her spotlight does not put you in darkness.</p>

<p>I look forward to seeing each of you next week in San Francisco. If you see me please feel free to say hi.</p>

<p>WWDC is once again upon us; be excellent to each other.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/06/03/why-so-serious/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Saving JSON to Core Data</title>
		<link>http://www.cimgf.com/2011/06/02/saving-json-to-core-data/</link>
		<comments>http://www.cimgf.com/2011/06/02/saving-json-to-core-data/#comments</comments>
		<pubDate>Thu, 02 Jun 2011 15:42:16 +0000</pubDate>
		<dc:creator>Tom Harrington</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[core-data]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1424</guid>
		<description><![CDATA[Hi, I&#8217;m new here. You may know me as @atomicbird on Twitter. Just a few days ago my book Core Data for iOS: Developing Data-Driven Applications for the iPad, iPhone, and iPod touch (co-written with the excellent Tim Isted) was published, and Matt invited me to contribute some Core Data tips to CIMGF. I&#8217;m going [...]]]></description>
			<content:encoded><![CDATA[<p>Hi, I&#8217;m new here. You may know me as <a href="http://twitter.com/#!/atomicbird">@atomicbird</a> on Twitter. Just a few days ago my book <a href="http://click.linksynergy.com/fs-bin/click?id=7x2bowiz7Uk&#038;offerid=163217.1350490&#038;type=2&#038;subid=0">Core Data for iOS: Developing Data-Driven Applications for the iPad, iPhone, and iPod touch</a> (co-written with the excellent Tim Isted) was published, and Matt invited me to contribute some Core Data tips to CIMGF. I&#8217;m going to start off discussing taking JSON data from a web service and converting it to Core Data storage. Along the way I&#8217;ll cover how to inspect managed objects to find out what attributes they have and what the attribute types are.</p>

<p>Publishing lead times being what they are, this post covers information not included in the book.
<span id="more-1424"></span></p>

<h2>The Ugly/Crude Way</h2>

<p>I&#8217;m going to assume that the incoming JSON more or less matches your managed object, i.e. that you have a JSON dictionary with keys that match the attribute names of your Core Data entities. Given a dictionary <code>jsonDict</code> that has been created by parsing incoming JSON data using a JSON library (<a href="https://github.com/TouchCode/TouchJSON">TouchJSON</a> and <a href="http://code.google.com/p/json-framework/">json-framework</a> are good choices) and a managed object imaginatively called <code>myObj</code>, the dead simple approach is to just do something like:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>myObj setValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>jsonDict objectForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;name&quot;</span><span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;name&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>myObj setValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>jsonDict objectForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;city&quot;</span><span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;city&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>myObj setValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>jsonDict objectForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;phone&quot;</span><span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;phone&quot;</span><span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>&#8230;and on and on and on ad nauseum. It works but it&#8217;s astoundingly ugly. It also makes maintenance more challenging, since any changes to the data structure require changes not only to your Core Data model and related managed object classes but also to your data import code.</p>

<h2>The Easy/Dangerous Way</h2>

<p>Cocoa provides a method that makes this much, much simpler. Thanks to key-value coding there&#8217;s a method in NSObject that reduces the above to a single line:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>myObj setValuesForKeysWithDictionary<span style="color: #002200;">:</span>jsonDict<span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>This will run through key/value pairs in <code>jsonDict</code> and set the same key/value pairs on <code>myObj</code>. The only caveat is that the key names must match, but that shouldn&#8217;t be a problem assuming you&#8217;ve named them the same in your data model.</p>

<p>Actually there&#8217;s one more caveat, and it&#8217;s a biggie. In this method, the keys contained in the dictionary determine what keys are used on the managed object. But what if the dictionary contains a key that&#8217;s not part of the entity description? Then your app crashes with an error about how the object is not key-value coding compliant for the key. Using this method here puts your app&#8217;s stability at the mercy of the web service you&#8217;re using. If you don&#8217;t have absolute control over the web service, you&#8217;re running serious risks using this method here. We can do better.</p>

<h2>Inspecting Managed Objects</h2>

<p>Since we&#8217;re using Core Data, we can use <code>NSEntityDescription</code> to inspect a managed object&#8217;s attributes and turn the logic above around. Instead of using the incoming dictionary to determine what key/value pairs to use, we can use the managed object.</p>

<p>You can look up the entity description for a managed object by asking for its <code>entity</code>. That gives you an <code>NSEntityDescription</code> which you can then ask for all kinds of useful information, like what attributes exist. That leads to a safer approach when converting from JSON:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>attributes <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>myObj entity<span style="color: #002200;">&#93;</span> attributesByName<span style="color: #002200;">&#93;</span>;
<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>attribute <span style="color: #a61390;">in</span> attributes<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">id</span> value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>jsonDict objectForKey<span style="color: #002200;">:</span>attribute<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>value <span style="color: #002200;">==</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #a61390;">continue</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#91;</span>myObj setValue<span style="color: #002200;">:</span>value forKey<span style="color: #002200;">:</span>attribute<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>This code iterates over the entity&#8217;s attributes, looks up a key in the dictionary for each of them, and applies that key/value pair to the managed object. That&#8217;s still nice and generic, and has the advantage that changes to incoming data won&#8217;t crash the app any more. It looks up values in the dictionary only for attributes that actually exist in the entity description. Extra dictionary keys are simply ignored.</p>

<p>The check for <code>nil</code> is there because the code does hit <em>all</em> of the entity&#8217;s attributes. If the entity has any attributes that aren&#8217;t present in the incoming data (a &#8220;favorites&#8221; flag, for example) the code would end up setting a nil value for the attribute. That could lead to accidentally wiping out data that you really want to keep.</p>

<h2>Handling Broken and Inconsistent JSON</h2>

<p>The <a href="http://www.json.org/">JSON standard</a> is quite clear about how to distinguish strings from numbers&#8211; basically, strings are surrounded by quotes and numbers are not. JSON <em>web services</em> however, are not always good about following this requirement. And even when they are, they are not always consistent from one record to another.</p>

<p>An example, similar to one I encountered recently: Size information for clothing. Sizes are provided by the web service and are typically something like &#8220;30-32&#8243;, &#8220;34-36&#8243;, etc. These are correctly quoted as strings in the JSON, and the app saves them as string attributes and displays them to the user as is.</p>

<p>But sometimes the size just has one number, e.g. &#8220;8&#8243;, &#8220;10&#8243;, etc. In this case the server drops the quotes, making them numbers. My JSON parser correctly produces an NSNumber. Only I want to save this in my entity&#8217;s string attribute! I can use Objective-C introspection to see if I received an NSString or an NSNumber from my JSON parser, but I also need to know what type the managed object expects for the property. I briefly considered breaking my JSON parser so that it would always return NSString, so at least I would know what to expect from it. Fortunately NSEntityDescription came to the rescue again.</p>

<p>Besides asking the entity description what its attribute names are, you can also inquire about the attribute types configured in the Core Data model. This is returned as an NSAttributeType. Using this, we can expand the code above to handle mismatched data types. It&#8217;s probably a good idea to abstract the code for easy reuse, too, so I&#8217;ll put it in a category on NSManagedObject:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> <span style="color: #400080;">NSManagedObject</span> <span style="color: #002200;">&#40;</span>safeSetValuesKeysWithDictionary<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>safeSetValuesForKeysWithDictionary<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>keyedValues
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>attributes <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self entity<span style="color: #002200;">&#93;</span> attributesByName<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>attribute <span style="color: #a61390;">in</span> attributes<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #a61390;">id</span> value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>keyedValues objectForKey<span style="color: #002200;">:</span>attribute<span style="color: #002200;">&#93;</span>;
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>value <span style="color: #002200;">==</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            <span style="color: #11740a; font-style: italic;">// Don't attempt to set nil, or you'll overwite values in self that aren't present in keyedValues</span>
            <span style="color: #a61390;">continue</span>;
        <span style="color: #002200;">&#125;</span>
        NSAttributeType attributeType <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>attributes objectForKey<span style="color: #002200;">:</span>attribute<span style="color: #002200;">&#93;</span> attributeType<span style="color: #002200;">&#93;</span>;
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>attributeType <span style="color: #002200;">==</span> NSStringAttributeType<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>value isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>value stringValue<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>attributeType <span style="color: #002200;">==</span> NSInteger16AttributeType<span style="color: #002200;">&#41;</span> || <span style="color: #002200;">&#40;</span>attributeType <span style="color: #002200;">==</span> NSInteger32AttributeType<span style="color: #002200;">&#41;</span> || <span style="color: #002200;">&#40;</span>attributeType <span style="color: #002200;">==</span> NSInteger64AttributeType<span style="color: #002200;">&#41;</span> || <span style="color: #002200;">&#40;</span>attributeType <span style="color: #002200;">==</span> NSBooleanAttributeType<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>value isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithInteger<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>value  integerValue<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>attributeType <span style="color: #002200;">==</span> NSFloatAttributeType<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>value isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithDouble<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>value doubleValue<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#125;</span>
        <span style="color: #002200;">&#91;</span>self setValue<span style="color: #002200;">:</span>value forKey<span style="color: #002200;">:</span>attribute<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></div></div>


<p>This code inspects the types of both the value found in the dictionary we created from the incoming JSON and the attribute on the managed object, and if there&#8217;s a string/number mismatch it modifies the value to make sure it matches what&#8217;s expected.</p>

<p>This is getting pretty useful. Not only is it a generic JSON-to-NSManagedObject conversion, it also handles mismatches between numeric and string types without needing any entity-specific information. It could be even better, though.</p>

<h2>Handling Dates</h2>

<p>JSON does not have a date type, but dates are nevertheless common in JSON. They&#8217;re just represented as strings using one date format or another. Only you probably want an NSDate, not a string. NSDateFormatter is really useful here, but wouldn&#8217;t it be nice to make the date conversion generic as well, so you don&#8217;t need to special-case your date attribute? Can you see where I&#8217;m going with this?</p>

<p>Having written the category method above, it&#8217;s not much more work to add an optional NSDateFormatter argument, and then to use it whenever an entity&#8217;s attribute expects a date. This modified version adds that argument, and an extra case to the &#8220;else &#8230; if&#8221; chain:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> <span style="color: #400080;">NSManagedObject</span> <span style="color: #002200;">&#40;</span>safeSetValuesKeysWithDictionary<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>safeSetValuesForKeysWithDictionary<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>keyedValues dateFormatter<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDateFormatter</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>dateFormatter
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>attributes <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self entity<span style="color: #002200;">&#93;</span> attributesByName<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>attribute <span style="color: #a61390;">in</span> attributes<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #a61390;">id</span> value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>keyedValues objectForKey<span style="color: #002200;">:</span>attribute<span style="color: #002200;">&#93;</span>;
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>value <span style="color: #002200;">==</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            <span style="color: #a61390;">continue</span>;
        <span style="color: #002200;">&#125;</span>
        NSAttributeType attributeType <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>attributes objectForKey<span style="color: #002200;">:</span>attribute<span style="color: #002200;">&#93;</span> attributeType<span style="color: #002200;">&#93;</span>;
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>attributeType <span style="color: #002200;">==</span> NSStringAttributeType<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>value isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>value stringValue<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>attributeType <span style="color: #002200;">==</span> NSInteger16AttributeType<span style="color: #002200;">&#41;</span> || <span style="color: #002200;">&#40;</span>attributeType <span style="color: #002200;">==</span> NSInteger32AttributeType<span style="color: #002200;">&#41;</span> || <span style="color: #002200;">&#40;</span>attributeType <span style="color: #002200;">==</span> NSInteger64AttributeType<span style="color: #002200;">&#41;</span> || <span style="color: #002200;">&#40;</span>attributeType <span style="color: #002200;">==</span> NSBooleanAttributeType<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>value isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithInteger<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>value integerValue<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>attributeType <span style="color: #002200;">==</span> NSFloatAttributeType<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;&amp;</span>  <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>value isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithDouble<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>value doubleValue<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>attributeType <span style="color: #002200;">==</span> NSDateAttributeType<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>value isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">&#40;</span>dateFormatter <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>dateFormatter dateFromString<span style="color: #002200;">:</span>value<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#125;</span>
        <span style="color: #002200;">&#91;</span>self setValue<span style="color: #002200;">:</span>value forKey<span style="color: #002200;">:</span>attribute<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></div></div>


<h2>Conclusion</h2>

<p>Saving JSON data to a managed object is one of those things that&#8217;s not as easy as it seems at first glance. Making it happen is easy enough, but making it happen safely in maintainable code can quickly get complicated. Fortunately, Core Data has your back and will help you work out what needs to happen along the way.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/06/02/saving-json-to-core-data/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>SecurVid HD [Advertisement]</title>
		<link>http://www.cimgf.com/2011/05/27/securvid-hd-advertisement/</link>
		<comments>http://www.cimgf.com/2011/05/27/securvid-hd-advertisement/#comments</comments>
		<pubDate>Fri, 27 May 2011 20:33:34 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Announcement]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1411</guid>
		<description><![CDATA[This is a short introductory article to welcome a new application to Zarra Studios. We are involved in a lot of contract work and frequently our clients will give us video files. These files can be demos, mock ups, advertisements, etc. As a developer on the move, I like to keep these with me and [...]]]></description>
			<content:encoded><![CDATA[<p>This is a short introductory article to welcome a new application to Zarra Studios.</p>

<p>We are involved in a lot of contract work and frequently our clients will give us video files.  These files can be demos, mock ups, advertisements, etc.</p>

<p>As a developer on the move, I like to keep these with me and on my iPad so that I can review them whenever I want.</p>

<p>Of course, Client A does not want Client B to be able to accidentally see their files.  Lawsuits happen that way.</p>

<p>To make this even more fun, everyone wants to borrow your iPad.  Everyone wants to touch it and play with it.  This increases the risk of the videos getting into the wrong hands.</p>

<p>From this, <a href='http://itunes.apple.com/us/app/securvid-hd/id431538573?mt=8&#038;ls=1'>SecurVid</a> was born.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2011/05/app_512.jpg" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2011/05/app_512-150x150.jpg" alt="" title="app_512" width="150" height="150" class="alignnone size-thumbnail wp-image-1412" /></a></p>

<h2>Features</h2>

<p>SecurVid is designed to put videos behind a password lock.  The videos are kept encrypted on disk and are not backed up to your computer that you sync your iPad with.  This means that it is not designed to be a storage system for your videos but a protection for videos you need access to but don&#8217;t want everyone who borrows your iPad to see.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2011/05/SS1.jpg" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2011/05/SS1-300x143.jpg" alt="" title="SS1" width="300" height="143" class="alignnone size-medium wp-image-1413" /></a></p>

<p>SecurVid has a lossy way to reset its password in case you forget it.  Enter the wrong password three times and it will offer to reset for you.  However that reset comes at a price; it will first delete all of your videos before offering to reset the password.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2011/05/SS2.jpg" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2011/05/SS2-300x214.jpg" alt="" title="SS2" width="300" height="214" class="alignnone size-medium wp-image-1414" /></a></p>

<p>Once you are into SecurVid you can watch the videos you have already loaded naturally. You can also add more videos via iTunes as well as from any other application that is configured with file sharing.  Therefore if a client emails you a video you can tap and press on the video file in mail on your iPad and load it into SecurVid.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2011/05/SS3.jpg" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2011/05/SS3-300x286.jpg" alt="" title="SS3" width="300" height="286" class="alignnone size-medium wp-image-1415" /></a></p>

<p>Likewise you can export videos from SecurVid either for emailing or for loading into another application. You can even mark a video as &#8220;unprotected&#8221; and allow iTunes to see it next time you plug in your iPad.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2011/05/SS4.jpg" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2011/05/SS4-300x219.jpg" alt="" title="SS4" width="300" height="219" class="alignnone size-medium wp-image-1416" /></a></p>

<h2>The Future</h2>

<p>This is the 1.0 release of SecurVid and has the core features that I/we needed in the application.  However it is just the beginning for this application.  As the application matures we will be adding additional features and continuing to release updates.</p>

<h2>Cost</h2>

<p>Because the 1.0 has only the core set of features we are offering it at an introductory price of $4.99.  That price will remain until the next set of features are added.  When that occurs we will increase the price up to the next appropriate level.  However if you bought the 1.0 you will get these upgrades for free.</p>

<p><a href='http://itunes.apple.com/us/app/securvid-hd/id431538573?mt=8&#038;ls=1'>SecurVid HD is available on the App Store now.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/05/27/securvid-hd-advertisement/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Core Data and Threads, Without the Headache</title>
		<link>http://www.cimgf.com/2011/05/04/core-data-and-threads-without-the-headache/</link>
		<comments>http://www.cimgf.com/2011/05/04/core-data-and-threads-without-the-headache/#comments</comments>
		<pubDate>Wed, 04 May 2011 20:12:56 +0000</pubDate>
		<dc:creator>Saul Mora</dc:creator>
				<category><![CDATA[Core Data]]></category>
		<category><![CDATA[GCD & Blocks]]></category>
		<category><![CDATA[NSOperation]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[core-data]]></category>
		<category><![CDATA[gcd]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1388</guid>
		<description><![CDATA[I know I mentioned we would talk about customizing the fetch requests, however, I have been working on some code related to the Active Record Fetching project, which I am renaming to MagicalRecord, that is also just as useful as fetching&#8211;threading. Whenever most cocoa developers mention threading and Core Data in the same sentence, the [...]]]></description>
			<content:encoded><![CDATA[<p>I know I mentioned we would talk about customizing the fetch requests, however, I have been working on some code related to the Active Record Fetching project, which I am renaming to MagicalRecord, that is also just as useful as fetching&#8211;threading.</p>

<p>Whenever most cocoa developers mention threading and Core Data in the same sentence, the reaction I see most often is that of mysticism and disbelief. For one, multithreaded programming in general is hard&#8211;hard to design correctly, hard to write correctly, and debugging threads is just asking for trouble. Introducing Core Data into that mix can seem like the straw that broke the camel&#8217;s back. However, by following a few simple rules and guidelines, and codifying them into a super simple pattern, one that may be familiar to you, we can achieve safer Core Data threading without the common headaches.</p>

<p><span id="more-1388"></span></p>

<p>Another reminder: the examples in this blog post will refer to the open source project on Github, <a href="http://github.com/magicalpanda/magicalrecord">MagicalRecord</a>, which is basically several helpful categories and classes I&#8217;ve written to extend the standard Core Data APIs.</p>

<h2 style="font-size: 1.5em">What would Apple do?</h2>

<p>Let&#8217;s start by looking up in the docs (see <a href="http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/CoreData/Articles/cdConcurrency.html">Concurrency with Core Data</a>) to see what needs to happen in order to set up Core Data to pass data objects across threads and perform save operations in the background. Summarizing the main points from the recommended approach:</p>

<ul>
    <li>Each thread should have its one NSManagedObjectContext</li>
    <li>NSManagedObjects themselves are <strong>not</strong> thread-safe</li>
    <li>NSManagedObjectIDs <strong>are</strong> thread-safe</li>
    <li>If you save in the background, you need to merge your changes to other contexts using one of the Core Data system notifications, <em>NSManagedObjectContextDidSaveNotification</em>.</li>
</ul>

<p>How do we do this in code? The most common solution is to create a custom NSOperation, and make sure we create and set up our new context in the main method of the operation, like so:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;MGPCoreDataOperation.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> MGPCoreDataOperation <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>context;
&nbsp;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> MGPCoreDataOperation
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>main
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>self setContext<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSManagedObjectContext</span> context<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">//perform my core data operations here</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></div></div>


<p>Remember to create the NSManagedObjectContext in the main method of your custom NSOperation, and not the init method. The main is the only one of the two that is guaranteed to be called from another thread. Your secondary NSManagedObjectContext needs to be created inside the thread where it will be used.</p>

<p>This solution is fairly straightforward, however, let&#8217;s think beyond this class. Using this approach, while a valid solution, is somewhat cumbersome to reuse. For every save operation using this technique you will:</p>

<ul>
    <li>need to subclass, or create this class via a template every time</li>
    <li>instantiate this objects on the main thread, and give it to an NSOperationQueue</li>
    <li>have to pass in object ids through a property</li>
</ul>

<p>This solution is for the heavy lifting algorithms such as parsing data in the background and saving it in once the parse is done, and all on a background thread. Let&#8217;s try a solution that is a little lighter weight, a little easier on the eyes, and uses one of the more fun and recent additions to Objective C&#8211;blocks and GCD.</p>

<h2 style="font-size: 1.5em">A small idea</h2>

<p>Before we get started with our threading adventure, we need to first seed our minds with a small idea that will help us for the remainder of this post. In the context of threading and UI, we need to examine the concept of a <em>Main Thread</em>. The <em>main thread</em> is different from other threads in that it is considered the foreground thread, and is the thread which runs the main runloop, which in turn, processes messages sent from outside your app such as taps or clicks, and sends them to your application. From this example, let&#8217;s introduce the concept of a Main Managed Object Context. This context is meant to only be accessed from the same thread as the UI. This context is also always available, as is the <em>Main Thread</em>, and Main Runloop. In the MagicalRecord helpers, I have implemented a defaultContext class method that provides access from anywhere.</p>

<p>The default Xcode Core Data application template promotes this idea by virtue of putting a reused managed object context in the app delegate. Both the app delegate, and the managed object context are implied singletons. MagicalRecord also keeps it&#8217;s default context in a single place for easy reuse in your applications, and is also a singleton-like pattern. But, unlike the application templates, it keeps its reference away from your app delegate. Technically speaking, moving the shared NSManagedObjectContext out of the app delegate is merely a preference, but my preference is to keep the application delegate as free from actual application responsibility as possible.</p>

<p>This main context provides some neat features. First, it let&#8217;s us simplify the find methods described in my <a href="http://www.cimgf.com/2011/03/13/super-happy-easy-fetching-in-core-data/">previous post</a>, while still having the option for a context parameter. Second, this lets us get started with Core Data very quickly since we can do fetching from the main thread on the main context, and not have cross thread issues. And third, and most importantly, we have a single context to which any background changes are merged. And if those benefits weren&#8217;t helpful enough, changes to observed managed object instance can immediately be acted upon by any UI components using KVO.</p>

<h2 style="font-size: 1.5em">Core Data, Blocks and GCD&#8230;oh my!</h2>

<p>Multithreading in Core Data is important when it comes to saving data in the store. While complex fetches can certainly take quite a bit of time to return, most frequently the bottleneck is during a save. As such, the goal in this solution is to make background saving easy and safe.</p>

<p>This block based solution is inspired by one of the newer iOS APIs for animating views. Blocks are incredibly powerful, and for Core Animation code, have greatly simplified animation code. A simple animation now looks like this:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">UIView <span style="color: #002200;">*</span>redView <span style="color: #002200;">=</span> ...;
<span style="color: #002200;">&#91;</span>UIView animateWithDuration<span style="color: #002200;">:</span><span style="color: #2400d9;">5.0</span>
		 animations<span style="color: #002200;">:^</span><span style="color: #002200;">&#123;</span>
			redView.alpha <span style="color: #002200;">=</span> <span style="color: #2400d9;">0.0</span>;
		 <span style="color: #002200;">&#125;</span>
 <span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>Can we use this paradigm to save Core Data objects on a background thread? What if we had a save API resembling this animation API? Let&#8217;s first think about the synchronous (aka. easy) case.  The API would probably look something like this:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> saveDataInContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>context<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>saveBlock;</pre></div></div>


<p>When using this API our code will resemble this sample:</p>


<div class="wp_syntax"><div class="code"><pre class="obj" style="font-family:monospace;">PersonEntity *person = ...;
NSManagedObjectID *objectID = [person objectID];
[NSManagedObjectHelper saveDataInContext:^(NSManagedObjectContext *localContext){
	PersonEntity *localPerson = (PersonEntity *)[localContext objectWithID:objectID];
&nbsp;
	//make my updates to localPerson here
	localPerson.name = @&quot;IronMan&quot;;
	//...more changes
}];</pre></div></div>


<p>While it&#8217;s not terribly important in this particular example because it&#8217;s all running in the same tread, I must remind you that NSManagedObjects are NOT thread-safe, but NSMangedObjectIDs are, so we need to pass an NSManagedObject&#8217;s object ID across the thread, or in this case, block boundary.</p>

<p>In order for this code sample to work, the implementation of the saveDataInContext method should be:</p>

<ul>
    <li>creating a new NSManagedObjectContext instance, AND</li>
    <li>setting up the both contexts with the proper merge policy, AND</li>
    <li>setting up the main context to listen to the background context to merge on save,</li>
    <li>sending that context as the parameter into the block for use by other code.</li>
</ul>

<p>This would make creating lightweight save or update operations as easy as creating a UIView block-based animation.</p>

<p>So, what would the body of this method look like? Let&#8217;s start the first item on the list.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>saveDataInContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>context<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>saveBlock
<span style="color: #002200;">&#123;</span>
	<span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>context <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSManagedObjectContext</span> context<span style="color: #002200;">&#93;</span>;			<span style="color: #11740a; font-style: italic;">//step 1</span>
	<span style="color: #002200;">&#91;</span>context setMergePolicy<span style="color: #002200;">:</span>NSMergeByPropertyObjectTrumpMergePolicy<span style="color: #002200;">&#93;</span>;				<span style="color: #11740a; font-style: italic;">//step 2</span>
	<span style="color: #002200;">&#91;</span>defaultContext setMergePolicy<span style="color: #002200;">:</span>NSMergeObjectByPropertyStoreTrumpMergePolicy<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>defaultContext observeContext<span style="color: #002200;">:</span>context<span style="color: #002200;">&#93;</span>;						<span style="color: #11740a; font-style: italic;">//step 3</span>
&nbsp;
	block<span style="color: #002200;">&#40;</span>context<span style="color: #002200;">&#41;</span>;										<span style="color: #11740a; font-style: italic;">//step 4</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>context hasChanges<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>								<span style="color: #11740a; font-style: italic;">//step 5</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>context save<span style="color: #002200;">&#93;</span>;  <span style="color: #11740a; font-style: italic;">//MagicalRecord will dump errors to the console with this save method</span>
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>This code uses some <a href="http://github.com/magicalpanda/magicalrecord">MagicalRecord</a> helper methods, but the steps as implemented are:</p>

<ul>
    <li>Step 1: Create the new context</li>
    <li>Step 2: Set the merge policy</li>
    <li>Step 3: Set up the notification</li>
    <li>Step 4: Call back our block with our newly created context that&#8217;s been set up properly.</li>
    <li>Step 5: Save the context if it has any changes</li>
</ul>

<p>Notice also, that in order for a merge to occur automatically, one context has to be set to win during the merge. In this case, we want the background context to win by telling the main context that we want the information in our data store to be the correct answer in the case of a conflict. Also notice that much of the setup of a second context is as simple as calling a single method. We can now build upon this simple foundation and introduce background threading for our saves. Since we&#8217;re using blocks, we can also take advantage of the Grand Central Dispatch APIs.</p>

<p>A background operation using our synchronous method can easily be written using GCD:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>saveDataInBackgroundWithContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>context<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>saveBlock
<span style="color: #002200;">&#123;</span>
	dispatch_async<span style="color: #002200;">&#40;</span>dispatch_get_global_queue<span style="color: #002200;">&#40;</span>DISPATCH_QUEUE_PRIORITY_BACKGROUND, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>self saveDataInContext<span style="color: #002200;">:</span>saveBlock<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>


<h2>Going the Distance</h2>

<p>But, can we do more? What is one neat feature of the UIView block animation APIs? Their ability to call a block when the animation has completed. How useful would it be to have a block of code called exactly after the changes to your object have been saved and merged? I thought so; let&#8217;s look again at a UIView animation API for inspiration:
<pre>+ (void)animateWithDuration:(NSTimeInterval)<em>duration</em> animations:(void (^)(void))<em>animations</em> completion:(void (^)(BOOL finished))<em>completion</em></pre>
And a usage sample, expanding on our previous UIView animation example:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">UIView <span style="color: #002200;">*</span>redView <span style="color: #002200;">=</span> ...;
<span style="color: #002200;">&#91;</span>UIView animateWithDuration<span style="color: #002200;">:</span><span style="color: #2400d9;">5.0</span>
		 animations<span style="color: #002200;">:^</span><span style="color: #002200;">&#123;</span>
			redView.alpha <span style="color: #002200;">=</span> <span style="color: #2400d9;">0.0</span>;
		 <span style="color: #002200;">&#125;</span>
		 completion<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span>  completed<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#123;</span>
			<span style="color: #002200;">&#91;</span>redView removeFromSuperview<span style="color: #002200;">&#93;</span>;
			<span style="color: #002200;">&#91;</span>redView release<span style="color: #002200;">&#93;</span>;
			redView <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
		 <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>To be safe, let&#8217;s make sure our completion block is called on the main thread while we&#8217;re at it.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>saveDataInBackgroundWithContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>context<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>saveBlock completion<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>completion
<span style="color: #002200;">&#123;</span>
	dispatch_async<span style="color: #002200;">&#40;</span>dispatch_get_global_queue<span style="color: #002200;">&#40;</span>DISPATCH_QUEUE_PRIORITY_BACKGROUND, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>self saveDataInContext<span style="color: #002200;">:</span>saveBlock<span style="color: #002200;">&#93;</span>;
&nbsp;
		dispatch_sync<span style="color: #002200;">&#40;</span>dispatch_get_main_queue<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
			completion<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
		<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>Now, you can save and reload, or update your data in a single place sort of like this:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"> 
<span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>listOfPeople <span style="color: #002200;">=</span> ...;
<span style="color: #002200;">&#91;</span>NSManagedObjectHelper saveDataInBackgroundWithContext<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>localContext<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>personInfo <span style="color: #a61390;">in</span> listOfPeople<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		PersonEntity <span style="color: #002200;">*</span>person <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>PersonEntity createInContext<span style="color: #002200;">:</span>localContext<span style="color: #002200;">&#93;</span>;
		<span style="color: #002200;">&#91;</span>person setValuesForKeysWithDictionary<span style="color: #002200;">:</span>personInfo<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span> completion<span style="color: #002200;">:^</span><span style="color: #002200;">&#123;</span>
	self.people <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>PersonEntity findAll<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>This small block of code does a lot for you. It,</p>

<ul>
    <li>creates and sets up a background Managed Object Context</li>
    <li>creates and sets up a background GCD queue</li>
    <li>saves the background context, which was set up to notify our Managed Object Context in the Main thread</li>
    <li>calls back your completion block on the main thread AFTER the changes have been pushed all the way to the persistent store</li>
</ul>

<p>However, there is one more thing we could add to help keep our saving simple. As it is now, the background operations are performed on a global background queue. I&#8217;ve encountered times where it is necessary to have a single dedicated GCD queue only for Core Data operations. In <a href="http://github.com/magicalpanda/magicalrecord">MagicalRecord</a>, we&#8217;ve defined a simple static function that allows access to a write only GCD queue.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">static</span> dispatch_queue_t coredata_background_save_queue;
&nbsp;
dispatch_queue_t background_save_queue<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>coredata_background_save_queue <span style="color: #002200;">==</span> <span style="color: #a61390;">NULL</span><span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        coredata_background_save_queue <span style="color: #002200;">=</span> dispatch_queue_create<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">&quot;com.magicalpanda.coredata.backgroundsaves&quot;</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #a61390;">return</span> coredata_background_save_queue;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>And this would only modify our background core data save method like so:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>saveDataInBackgroundWithContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>context<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>saveBlock completion<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>completion
<span style="color: #002200;">&#123;</span>
	dispatch_async<span style="color: #002200;">&#40;</span>coredata_background_save_queue<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>self saveDataInContext<span style="color: #002200;">:</span>saveBlock<span style="color: #002200;">&#93;</span>;
&nbsp;
		dispatch_sync<span style="color: #002200;">&#40;</span>dispatch_get_main_queue<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
			completion<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
		<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>Using blocks, GCD and a little bit of convention, we&#8217;ve helped to make multithreaded Core Data code much easier to write and stay consistent with Apple&#8217;s recommended methods. Not only that, but this solution consolodates much of the manual boilerplate setup required to properly save data in the background and safely update data throughout your applications.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/05/04/core-data-and-threads-without-the-headache/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Super Happy Easy Fetching in Core Data</title>
		<link>http://www.cimgf.com/2011/03/13/super-happy-easy-fetching-in-core-data/</link>
		<comments>http://www.cimgf.com/2011/03/13/super-happy-easy-fetching-in-core-data/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 05:30:04 +0000</pubDate>
		<dc:creator>Saul Mora</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[core-data]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1351</guid>
		<description><![CDATA[First up, I want to thank Matt Long and Marcus Zarra for allowing me to guest post on CIMGF. This post is the first in a short series of topics describing how to I&#8217;ve made using Core Data a little simpler without giving up the power features you still need. The full project from which [...]]]></description>
			<content:encoded><![CDATA[<p>First up, I want to thank Matt Long and Marcus Zarra for allowing me to guest post on CIMGF. This post is the first in a short series of topics describing how to I&#8217;ve made using Core Data a little simpler without giving up the power features you still need. The full project from which this series is derived is available on <a href="http://github.com/magicalpanda/activerecord-fetching-for-core-data">github</a>.</p>

<p>Core Data, for both iPhone and Mac, is a very powerful framework for persisting your objects out of memory, and into a more permanent storage medium. With the enormous power of Core Data, it can be easy to slip into the trap of thinking that Core Data is very complex.</p>

<p><span id="more-1351"></span></p>

<h2>Easy Fetches</h2>

<p>When I was first learning about Core Data, I naively thought that getting data from a data store would be easy. Core Data is a framework for fetching and persisting data, after all! I eventually learned that the minimum code required in order to fetch data from the store resembled this:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>context <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIApplication sharedApplication<span style="color: #002200;">&#93;</span> delegate<span style="color: #002200;">&#93;</span> managedObjectContext<span style="color: #002200;">&#93;</span>;
<span style="color: #400080;">NSFetchRequest</span> <span style="color: #002200;">*</span>request <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSFetchRequest</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #400080;">NSEntityDescription</span> <span style="color: #002200;">*</span>entity <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSEntityDescription</span> entityForName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;MyEntity&quot;</span> inManagedObjectContext<span style="color: #002200;">:</span>context<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request setEntity<span style="color: #002200;">:</span>entity<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #400080;">NSPredicate</span> <span style="color: #002200;">*</span>searchFilter <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSPredicate</span> predicateWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;attribute = %@&quot;</span>, searchingFor<span style="color: #002200;">&#93;</span>;
<span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
<span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>results <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>context executeFetchRequest<span style="color: #002200;">:</span>request error<span style="color: #002200;">:&amp;</span>amp;error<span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>This is quite a bit of code for pulling data out of a store, and this doesn&#8217;t even include error handling. I&#8217;ve often seen this code copied and pasted where needed in other projects. Some developers even use code snippets to generate these fetch requests. All that similar code can easily become a nightmare to maintain once your app starts to contain many entities. What I wanted was a little more automagic.</p>

<p>About a year ago, I ran across <a href="http://cocoawithlove.com/2008/03/core-data-one-line-fetch.html">this post</a> by Matt Gallagher on his terrific blog <a href="http://cocoawithlove.com/">Cocoa with Love</a>, which introduced the idea of the &#8220;one line fetch&#8221;. The blog post had a good idea, and a simple example of how to implement such an idea, however it occurred to me there were some ways I could enhance the example. The first was the use of the entity name in the method as a string parameter. This is required for the case that there are no custom NSManagedObject subclasses for your entities. And second, the example still required the helper methods to be part of your view controllers.</p>

<p>One reason to use helper methods to generate your fetch requests is that your code remains <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">dry</a>. That is, you remove duplication. Once you start using Core Data, you quickly realize that many requests start to look alike after a while. By consolidating this logic into a single method, or set of methods, we can be sure that optimizing one request can improve many requests. But perhaps more important is that by condensing the code, and removing the repetitive parts, you can easily see at a glance what the code intends to do, with the details only a method call away.</p>

<h2>Dynamically Generating your Fetch Requests</h2>

<p>In order to request data from your Core Data store, you must start with an NSFetchRequest. As the sample request above showed, we&#8217;ll need to at least set the entity for the data we&#8217;re intending to fetch.</p>

<p>I always use <a href="https://github.com/rentzsch/mogenerator">mogenerator</a> to generate custom subclasses for my Core Data entities. With each custom subclass, you get some valuable information that can help ease the process of building helper methods to autogenerate fetch requests. The primary bit of useful information is a Class object that is related to your Entity. If your entity names and class names are identical, it&#8217;s fairly easy to derive a class method to create the correct NSEntityDescription at runtime by using the <em>NSStringFromClass()</em> function. However, with mogenerator, a convenience method that returns the entity description required for fetch requests is auto generated for you called <em>entityInManagedObjectContext:</em>.</p>

<p>When you have a class method, the self object refers to the current Class object, from which you can get a string to look up the proper entity description required for a lookup. This is a big step in autogenerating requests. In the case of mogenerated code, we can check if the current Class responds to a particular selector, entityInManagedObjectContext:, and call that instead. For now, assume that the following methods are class methods in an NSManagedObject subclass called MyEntity.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSEntityDescription</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>entityDescriptionInContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>context
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>self respondsToSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>entityInManagedObjectContext<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span> ?
        <span style="color: #002200;">&#91;</span>self performSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>entityInManagedObjectContext<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span> withObject<span style="color: #002200;">:</span>context<span style="color: #002200;">&#93;</span> <span style="color: #002200;">:</span>
        <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSEntityDescription</span> entityForName<span style="color: #002200;">:</span>NSStringFromClass<span style="color: #002200;">&#40;</span>self<span style="color: #002200;">&#41;</span> inManagedObjectContext<span style="color: #002200;">:</span>context<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>Using this method, we can dynamically determine the entity for which we should fetch data. So, let&#8217;s start by creating a class method to  find all instances of a particular entity in the store:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>findAllObjects
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>context <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIApplication sharedApplication<span style="color: #002200;">&#93;</span> delegate<span style="color: #002200;">&#93;</span> managedObjectContext<span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSEntityDescription</span> <span style="color: #002200;">*</span>entity <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self entityDescriptionInContext<span style="color: #002200;">:</span>context<span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSFetchRequest</span> <span style="color: #002200;">*</span>request <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSFetchRequest</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span> autorelease<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>request setEntity<span style="color: #002200;">:</span>entity<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>context executeFetchRequest<span style="color: #002200;">:</span>request error<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>And using this method from, for example a View Controller in our app, we could simply call:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>MyEntity findAllObjects<span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>The niceness of this syntax over the fully verbose glob is that at a glance I can quickly see what&#8217;s going on. In this case, I want all the instances of MyEntity in the store, in no particular order. Simple and to the point without having to decipher a series of NSFetchRequest customizations (which would be minimal for this example). In this case, we&#8217;re passing a message to the class method on MyEntity.</p>

<p>Next, we need to set some default error handling, and we have a simple way to find all objects in a store that are MyEntity instances.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>findAllObjects
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>context <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIApplication sharedApplication<span style="color: #002200;">&#93;</span> delegate<span style="color: #002200;">&#93;</span> managedObjectContext<span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSEntityDescription</span> <span style="color: #002200;">*</span>entity <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self entityDescriptionInContext<span style="color: #002200;">:</span>context<span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSFetchRequest</span> <span style="color: #002200;">*</span>request <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSFetchRequest</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span> autorelease<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>request setEntity<span style="color: #002200;">:</span>entity<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
    <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>results <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>context executeFetchRequest<span style="color: #002200;">:</span>request error<span style="color: #002200;">:&amp;</span>amp;error<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>error <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
      <span style="color: #11740a; font-style: italic;">//handle errors</span>
    <span style="color: #002200;">&#125;</span>
    <span style="color: #a61390;">return</span> results;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>I&#8217;m not explicitly adding error handling here, however inspecting the error object will give you some useful information to track down Core Data issues, such as validation errors, that might prevent your data from being saved. But there are two problems here. First, we don&#8217;t always want to use the default context from the Application Delegate. Second, and more importantly, we should be able to use this for other entities in the store.</p>

<p>Addressing the first issue&#8211;the matter of specifying the context&#8211;this is important because there will be cases where we need to perform some operation on this data in the background on another thread. The proper way to do that in Core Data is to create another context, so let&#8217;s make the context a method parameter:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>findAllObjectsInContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>context
<span style="color: #002200;">&#123;</span>
    ...
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>and we can still use the simple version of the find method like this:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> findAllObjects
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>self findAllObjectsInContext<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIApplication sharedApplication<span style="color: #002200;">&#93;</span> delegate<span style="color: #002200;">&#93;</span> managedObjectContext<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>So, now we have two methods that help find entities in our store, and the context is an injectable dependency. Fancy&#8230;and helpful for those cases involving threads.</p>

<p>The other problem was the matter of reusing this method across any custom NSManagedObject subclass. All objects that store data for you in Core Data are instances of or subclasses of NSManagedObject. The easiest way to reuse this method in this case is via a category. However, by placing these methods in a category of NSManagedObject, rather than the MyEntity subclass, all subclasses of NSManagedObject will inherit them at runtime. This means all entities in our store will have this nice helper method for retrieving all instances.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">//NSManagedObject+EasyFetching.h</span>
<span style="color: #a61390;">@interface</span> <span style="color: #400080;">NSManagedObject</span> <span style="color: #002200;">&#40;</span>EasyFetching<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSEntityDescription</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>entityDescriptionInContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>context;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>findAllObjects;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>findAllObjectsInContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>context;
&nbsp;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">//NSManagedObject+EasyFetching.m</span>
<span style="color: #a61390;">@implementation</span> <span style="color: #400080;">NSManagedObject</span> <span style="color: #002200;">&#40;</span>EasyFetching<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSEntityDescription</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>entityDescriptionInContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>context;
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>self respondsToSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>entityInManagedObjectContext<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span> ?
    <span style="color: #002200;">&#91;</span>self performSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>entityInManagedObjectContext<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span> withObject<span style="color: #002200;">:</span>context<span style="color: #002200;">&#93;</span> <span style="color: #002200;">:</span>
    <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSEntityDescription</span> entityForName<span style="color: #002200;">:</span>NSStringFromClass<span style="color: #002200;">&#40;</span>self<span style="color: #002200;">&#41;</span> inManagedObjectContext<span style="color: #002200;">:</span>context<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>findAllObjects;
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span>context <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIApplication sharedApplication<span style="color: #002200;">&#93;</span> delegate<span style="color: #002200;">&#93;</span> managedObjectContext<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>self findAllObjectsInContext<span style="color: #002200;">:</span>context<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>findAllObjectsInContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>context;
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSEntityDescription</span> <span style="color: #002200;">*</span>entity <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self entityDescriptionInContext<span style="color: #002200;">:</span>context<span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSFetchRequest</span> <span style="color: #002200;">*</span>request <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSFetchRequest</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span> autorelease<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>request setEntity<span style="color: #002200;">:</span>entity<span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
    <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>results <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>context executeFetchRequest<span style="color: #002200;">:</span>request error<span style="color: #002200;">:&amp;</span>amp;error<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>error <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        <span style="color: #11740a; font-style: italic;">//handle errors</span>
    <span style="color: #002200;">&#125;</span>
    <span style="color: #a61390;">return</span> results;
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></div></div>


<p>So now we have a class level find method on any NSManagedObject that will:</p>

<ul>
    <li>create the fetch request based on the class,</li>
    <li>execute that request</li>
    <li>use the same error handling for all requests (this is handy for logging core data errors to the console)</li>
</ul>

<p>And, in addition, we now have a place to put any custom helper methods. Since these methods are categories, they won&#8217;t interfere with any current fetching code already in your apps. These methods also have the handy side effect of being included in the type-ahead list in Xcode so they are there when you need them.</p>

<p>Next time, we&#8217;ll discuss how to handle other common request operations such as filtering, prefetching keys and even returning only one object.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/03/13/super-happy-easy-fetching-in-core-data/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Subduing CATiledLayer</title>
		<link>http://www.cimgf.com/2011/03/01/subduing-catiledlayer/</link>
		<comments>http://www.cimgf.com/2011/03/01/subduing-catiledlayer/#comments</comments>
		<pubDate>Tue, 01 Mar 2011 06:01:15 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1321</guid>
		<description><![CDATA[Many technologies we use as Cocoa/Cocoa Touch developers stand untouched by the faint of heart because often we simply don&#8217;t understand them and employing them can seem a daunting task. One of those technologies is found in Core Animation and is referred to as the CATiledLayer. It seems like a magical sort of technology because [...]]]></description>
			<content:encoded><![CDATA[<p>Many technologies we use as Cocoa/Cocoa Touch developers stand untouched by the faint of heart because often we simply don&#8217;t understand them and employing them can seem a daunting task. One of those technologies is found in Core Animation and is referred to as the CATiledLayer. It seems like a magical sort of technology because so much of its implementation is a bit of a black box and this fact contributes to it being misunderstood. CATiledLayer simply provides a way to draw very large images without incurring a severe memory hit. This is important no matter where you&#8217;re deploying, but it especially matters on iOS devices as memory is precious and when the OS tells you to free up memory, you better be able to do so or your app will be brought down. This blog post is intended to demonstrate that CATiledLayer works as advertised and implementing it is not as hard as it may have once seemed.
<span id="more-1321"></span></p>

<p><a href="http://www.cimgf.com/files/BitmapSlice.zip">Download Demo Project</a></p>

<h2>The Trick Is In Listening To The View</h2>

<p>Let me cut to the chase here and clue you in on what you need to do. The easiest way to take advantage of the CATiledLayer is to create a UIView based subclass and override the +layerClass class method to return a [CATiledLayer class].</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> layerClass
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>CATiledLayer class<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>Then, you just need to override drawRect: and draw what it tells you to draw. That&#8217;s it! Listen to the UIView. It&#8217;s telling you in drawRect: which rectangle it wants to draw. So while your user is scrolling a scroll view that contains your view, for example, drawRect: will be getting called continuously. You just need to calculate how that rectangle corresponds to the image you&#8217;re wanting to draw.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>drawRect<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGRect<span style="color: #002200;">&#41;</span>rect
<span style="color: #002200;">&#123;</span>
  <span style="color: #11740a; font-style: italic;">// You cant get the current context if you need it.</span>
   CGContextRef context <span style="color: #002200;">=</span> UIGraphicsGetCurrentContext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
  <span style="color: #11740a; font-style: italic;">// Your drawing code here ...</span>
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>I&#8217;ll show you a fuller implementation of drawRect: later. Feel free to skip there now or even download the demo project if you want to see the project in action. First I&#8217;m going to discuss how we get our tiles and truly take advantage of the memory use reduction we get from the CATiledLayer.</p>

<h2>The Downside Is Tiling the Image</h2>

<p>So, now that you&#8217;ve implemented a UIView derived subclass that overrides drawRect: performance is going to improve drastically, right? Well, unfortunately, not exactly. If you pull the entire image into memory with -imageNamed or even -imageWithContentsOfFile, you&#8217;re going to be up against the exact same memory problem you had before using a tiled layer. So what are the solutions? Well, if there were a way to map tiles to bytes on disk, that would be great, but unfortunately that is far more complicated and I’m not even sure it&#8217;s possible. In the end, we have to actually tile the image manually and store the images on disk to be loaded on demand.</p>

<p>So, the first question I asked when I realized this is can I do the tiling programmatically and write the files out to disk or do I need to slice them up in a photo editor manually? Just like everything in programming, there are tradeoffs between various solutions. If you have a different part of your workflow where it makes sense to tile the images before sending them to the device, I would choose that solution, however, that doesn&#8217;t seem terribly likely. In most cases you&#8217;re probably going to need to tile the images on device programmatically. If that&#8217;s true, then I suggest that you don&#8217;t just tile every image, but rather set a threshold size. If your images reach a certain dimension, only tile those since it will take some time and processing power to do so.</p>

<p>Of course, you&#8217;re going to want to do your tiling on a background thread as to not block your user interface, but here is some basic image tiling code that will write your image tiles to disk. You can place this in an NSOperation or use a block and run it on a background queue.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>saveTilesOfSize<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGSize<span style="color: #002200;">&#41;</span>size 
               forImage<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIImage<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image 
            toDirectory<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>directoryPath 
            usingPrefix<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>prefix
<span style="color: #002200;">&#123;</span>
  CGFloat cols <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>image size<span style="color: #002200;">&#93;</span>.width <span style="color: #002200;">/</span> size.width;
  CGFloat rows <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>image size<span style="color: #002200;">&#93;</span>.height <span style="color: #002200;">/</span> size.height;
&nbsp;
  <span style="color: #a61390;">int</span> fullColumns <span style="color: #002200;">=</span> floorf<span style="color: #002200;">&#40;</span>cols<span style="color: #002200;">&#41;</span>;
  <span style="color: #a61390;">int</span> fullRows <span style="color: #002200;">=</span> floorf<span style="color: #002200;">&#40;</span>rows<span style="color: #002200;">&#41;</span>;
&nbsp;
  CGFloat remainderWidth <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>image size<span style="color: #002200;">&#93;</span>.width <span style="color: #002200;">-</span> 
                          <span style="color: #002200;">&#40;</span>fullColumns <span style="color: #002200;">*</span> size.width<span style="color: #002200;">&#41;</span>;
  CGFloat remainderHeight <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>image size<span style="color: #002200;">&#93;</span>.height <span style="color: #002200;">-</span> 
                          <span style="color: #002200;">&#40;</span>fullRows <span style="color: #002200;">*</span> size.height<span style="color: #002200;">&#41;</span>;
&nbsp;
&nbsp;
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>cols &gt; fullColumns<span style="color: #002200;">&#41;</span> fullColumns<span style="color: #002200;">++</span>;
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>rows &gt; fullRows<span style="color: #002200;">&#41;</span> fullRows<span style="color: #002200;">++</span>;
&nbsp;
  CGImageRef fullImage <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>image CGImage<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> y <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>; y &lt; fullRows; <span style="color: #002200;">++</span>y<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> x <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>; x &lt; fullColumns; <span style="color: #002200;">++</span>x<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      CGSize tileSize <span style="color: #002200;">=</span> size;
      <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>x <span style="color: #002200;">+</span> <span style="color: #2400d9;">1</span> <span style="color: #002200;">==</span> fullColumns <span style="color: #002200;">&amp;&amp;</span> remainderWidth &gt; <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #11740a; font-style: italic;">// Last column</span>
        tileSize.width <span style="color: #002200;">=</span> remainderWidth;
      <span style="color: #002200;">&#125;</span>
      <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>y <span style="color: #002200;">+</span> <span style="color: #2400d9;">1</span> <span style="color: #002200;">==</span> fullRows <span style="color: #002200;">&amp;&amp;</span> remainderHeight &gt; <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #11740a; font-style: italic;">// Last row</span>
        tileSize.height <span style="color: #002200;">=</span> remainderHeight;
      <span style="color: #002200;">&#125;</span>
&nbsp;
      CGImageRef tileImage <span style="color: #002200;">=</span> CGImageCreateWithImageInRect<span style="color: #002200;">&#40;</span>fullImage, 
                                        <span style="color: #002200;">&#40;</span>CGRect<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#123;</span><span style="color: #002200;">&#123;</span>x<span style="color: #002200;">*</span>size.width, y<span style="color: #002200;">*</span>size.height<span style="color: #002200;">&#125;</span>, 
                                          tileSize<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
      <span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>imageData <span style="color: #002200;">=</span> UIImagePNGRepresentation<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>UIImage imageWithCGImage<span style="color: #002200;">:</span>tileImage<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
      <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>path <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@/%@%d_%d.png&quot;</span>, 
                        directoryPath, prefix, x, y<span style="color: #002200;">&#93;</span>;
      <span style="color: #002200;">&#91;</span>imageData writeToFile<span style="color: #002200;">:</span>path atomically<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>    
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Let me walk you through this a little bit. We pass in the size of the tiles we want to break our image into. We pass in the image itself, the directory we want to save it to, and finally a prefix that we will use as a unique identifier for the file names for the image in question. We need this so that we can retrieve them again later when we&#8217;re ready display them.</p>

<p>The first thing we do is calculate the number of tiles we&#8217;re going to have in columns and rows by dividing the total width by the tile width and the total height by the tile height. The result is a floating point number. We then get the number of columns and rows that are full sized tiles by using floorf(). We then calculate the width of the last column and the height of last row. Next we iterate through the entire grid of what will soon be tiled images, columns per row. Then we extract the image data at the rect in question and write its contents to disk using an NSData. The filename format we&#8217;re using takes into account the x and y positions in our grid of tiles such that an image would have its tiles named:</p>

<p><pre>
&lt;directory&gt;/&lt;prefix&gt;x_y.png
</pre></p>

<p>Where directory and prefix are the strings passed into the function. The .png extension here is really just for clarity. It is completely unnecessary.</p>

<h2>Implementing Draw Rect</h2>

<p>The first implementation of CATiledLayer expected that you would create a delegate for your layer and then override</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>drawLayer<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CALayer<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>theLayer 
            inContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGContextRef<span style="color: #002200;">&#41;</span>theContext</pre></div></div>


<p>This was error prone for several reasons. The trouble was you couldn&#8217;t use both UIKit and Core Graphics calls to draw in the layer which people would often do. They would soon start asking <a href="http://stackoverflow.com/questions/2295151/catiledlayer-drawing-crash">why their app was crashing</a> and would discover that the problem could be solved by only drawing using only Core Graphics.</p>

<p>Now, in iOS4, things have gotten much easier. You can simply override drawRect: in your UIView subclass and everything works correctly. To draw my layer correctly, I adapted the drawing code you find in the <a href="https://deimos.apple.com/WebObjects/Core.woa/BrowsePrivately/adc.apple.com.4092349126.04109539109.4144345585?i=1699219987">PhotoScroller sample code from the WWDC 2010 sessions</a> (Link opens iTunes). It looks like this:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>drawRect<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGRect<span style="color: #002200;">&#41;</span>rect <span style="color: #002200;">&#123;</span>
 	CGContextRef context <span style="color: #002200;">=</span> UIGraphicsGetCurrentContext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
  CGSize tileSize <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>CGSize<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#123;</span><span style="color: #2400d9;">256</span>, <span style="color: #2400d9;">256</span><span style="color: #002200;">&#125;</span>;
&nbsp;
  <span style="color: #a61390;">int</span> firstCol <span style="color: #002200;">=</span> floorf<span style="color: #002200;">&#40;</span>CGRectGetMinX<span style="color: #002200;">&#40;</span>rect<span style="color: #002200;">&#41;</span> <span style="color: #002200;">/</span> tileSize.width<span style="color: #002200;">&#41;</span>;
  <span style="color: #a61390;">int</span> lastCol <span style="color: #002200;">=</span> floorf<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>CGRectGetMaxX<span style="color: #002200;">&#40;</span>rect<span style="color: #002200;">&#41;</span><span style="color: #002200;">-</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">/</span> tileSize.width<span style="color: #002200;">&#41;</span>;
  <span style="color: #a61390;">int</span> firstRow <span style="color: #002200;">=</span> floorf<span style="color: #002200;">&#40;</span>CGRectGetMinY<span style="color: #002200;">&#40;</span>rect<span style="color: #002200;">&#41;</span> <span style="color: #002200;">/</span> tileSize.height<span style="color: #002200;">&#41;</span>;
  <span style="color: #a61390;">int</span> lastRow <span style="color: #002200;">=</span> floorf<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>CGRectGetMaxY<span style="color: #002200;">&#40;</span>rect<span style="color: #002200;">&#41;</span><span style="color: #002200;">-</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">/</span> tileSize.height<span style="color: #002200;">&#41;</span>;
&nbsp;
  <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> row <span style="color: #002200;">=</span> firstRow; row &lt;<span style="color: #002200;">=</span> lastRow; row<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> col <span style="color: #002200;">=</span> firstCol; col &lt;<span style="color: #002200;">=</span> lastCol; col<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      UIImage <span style="color: #002200;">*</span>tile <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self tileAtCol<span style="color: #002200;">:</span>col row<span style="color: #002200;">:</span>row<span style="color: #002200;">&#93;</span>;
&nbsp;
      CGRect tileRect <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span>tileSize.width <span style="color: #002200;">*</span> col, 
                         tileSize.height <span style="color: #002200;">*</span> row,
                         tileSize.width, tileSize.height<span style="color: #002200;">&#41;</span>;
&nbsp;
      tileRect <span style="color: #002200;">=</span> CGRectIntersection<span style="color: #002200;">&#40;</span>self.bounds, tileRect<span style="color: #002200;">&#41;</span>;
&nbsp;
      <span style="color: #002200;">&#91;</span>tile drawInRect<span style="color: #002200;">:</span>tileRect<span style="color: #002200;">&#93;</span>;
&nbsp;
      <span style="color: #11740a; font-style: italic;">// Draw a white line around the tile border so </span>
      <span style="color: #11740a; font-style: italic;">// we can see it</span>
      <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIColor whiteColor<span style="color: #002200;">&#93;</span> set<span style="color: #002200;">&#93;</span>;
      CGContextSetLineWidth<span style="color: #002200;">&#40;</span>context, <span style="color: #2400d9;">6.0</span><span style="color: #002200;">&#41;</span>;
      CGContextStrokeRect<span style="color: #002200;">&#40;</span>context, tileRect<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Our view port in the app is set by the frame of the scroll view. This view is a lot larger than a single tile, which we have set to the default size of 256 x 256. That means we need to find all of the tiles that need to be drawn for displaying in the view port. So, we calculate the first column, last column, first row, and last row. This tells us where within the image we need to start and stop drawing. It also tells us which tiles we need to load. Once we&#8217;ve got all of these rows and columns calculated, we can then iterate through them and grab the tile for the current row and column using the same filename format we used to save the files in the first place. The code to load the image tiles looks like this:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>UIImage<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>tileAtCol<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span>col row<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span>row
<span style="color: #002200;">&#123;</span>
  <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>path <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@/%@%d_%d.png&quot;</span>, tileDirectory, tileTag, col, row<span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>UIImage imageWithContentsOfFile<span style="color: #002200;">:</span>path<span style="color: #002200;">&#93;</span>;  
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Notice we&#8217;re using -imageWithContentsOfFile rather than -imageNamed, since -imageNamed actually caches the image in memory&#8211;which we don&#8217;t want. If we used that, we would be right back at our memory usage issue after scrolling around for a few minutes.</p>

<h2>Conclusion</h2>

<p>Using the CATiledLayer makes a lot of sense when memory is of the essence, which it is much of the time when doing iOS development. Examples from Apple and other places do a good job showing how you can use a tiled layer for use with PDFs, but if you want to tile an image, things are a little more complicated. I hope this post has served to help you better understand this powerful Core Animation layer. Until next time.</p>

<p><a href="http://www.cimgf.com/files/BitmapSlice.zip">Download Demo Project</a></p>

<h2>Notes on the Demo Project</h2>

<p>When running on the device the image I am tiling is just too large to be tiled completely before the app uses up too much memory and is killed. You will probably want to run in the simulator to see the tiling finish. As noted in the code comments, you un-comment the tiling code and do a first run with the app allowing it to finish tiling. Then, stop the app and re-comment that tiling code and it will just load and display the tiles it created without having to go through that tiling again. I suppose I could have made the tiling code get called in response to a button tap or something like that, but I&#8217;ll leave that as an exercise for the reader. Contact me through the comments below if you have any problems or questions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/03/01/subduing-catiledlayer/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Revisiting git tags and building</title>
		<link>http://www.cimgf.com/2011/02/20/revisiting-git-tags-and-building/</link>
		<comments>http://www.cimgf.com/2011/02/20/revisiting-git-tags-and-building/#comments</comments>
		<pubDate>Mon, 21 Feb 2011 00:14:33 +0000</pubDate>
		<dc:creator>Fraser Hess</dc:creator>
				<category><![CDATA[AppStore]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[microISV]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1289</guid>
		<description><![CDATA[A couple of years ago I posted my scripts for tagging and building. The build script doesn&#8217;t work so well for the App Stores and the Build and Archive-based submission process, so here&#8217;s an updated approach that works inside Xcode. (Same as my last article, I&#8217;m still using git, the tag.sh script, and Apple Generic [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of years ago I <a href="http://www.cimgf.com/2009/07/06/from-hacker-to-microisv-tagging-building-and-releasing/">posted my scripts</a> for tagging and building. The build script doesn&#8217;t work so well for the App Stores and the <strong>Build and Archive</strong>-based submission process, so here&#8217;s an updated approach that works inside Xcode. (Same as my last article, I&#8217;m still using git, the tag.sh script, and Apple Generic Versioning (agv).)</p>

<ol>
    <li>In your Xcode project, create a Shell Script target called <strong>GenGitVersion</strong>.</li>
    <li>Insert the following script in GenGitVersion&#8217;s Run Script phase, replacing the path to your git executable if need be:


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #007800;">git</span>=<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>local<span style="color: #000000; font-weight: bold;">/</span>git<span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span><span style="color: #c20cb9; font-weight: bold;">git</span>
<span style="color: #007800;">version</span>=<span style="color: #000000; font-weight: bold;">`</span><span style="color: #007800;">$git</span> describe<span style="color: #000000; font-weight: bold;">`</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;#define GIT_VERSION <span style="color: #007800;">$version</span>&quot;</span> <span style="color: #000000; font-weight: bold;">&gt;</span> InfoPlist.h
<span style="color: #c20cb9; font-weight: bold;">touch</span> Info.plist</pre></td></tr></table></div>


</li>
    <li>Make GenGitVersion a dependency of your main target.</li>
    <li>Add &#8220;InfoPlist.h&#8221; to your .gitignore file.</li>
    <li>In your main target&#8217;s build settings:</li>
<ol type=a>
    <li>Turn on <strong>Preprocess Info.plist File</strong></li>
    <li>Set <strong>Info.plist Preprocessor Prefix File</strong> to InfoPlist.h</li>
</ol>
    <li>In your app&#8217;s Info.plist set the <strong>Bundle versions string, short</strong> to GIT_VERSION</li>
</ol>

<p>Now each time you build the main target, the version will be populated in the build&#8217;s Info.plist.</p>

<p><strong>Examples</strong><br /></p>

<ul>
<li>If you tag a commit, the version returned by <code>git describe</code> is the tag name.</li
<li>If the current commit isn&#8217;t tagged, you&#8217;ll get the most recent tag plus the number of additional commits and an abbreviated commit name. Here&#8217;s a 1.0b1 tag with 2 additional commits: 1.0b1-2-g3925f3b. This can be a good way to identify a private developer build.</li>
<li>You can optionally add <code>--dirty</code> to <code>git describe</code> and the version will have <nobr>-dirty</nobr> appended if there are uncommitted changes to your working tree.</li>
<li><code>git describe</code> will fail if there are no tags in the current working tree.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/02/20/revisiting-git-tags-and-building/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Passing around a NSManagedObjectContext on iOS</title>
		<link>http://www.cimgf.com/2011/01/07/passing-around-a-nsmanagedobjectcontext-on-the-iphone/</link>
		<comments>http://www.cimgf.com/2011/01/07/passing-around-a-nsmanagedobjectcontext-on-the-iphone/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 19:23:46 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1274</guid>
		<description><![CDATA[This article is reprinted from the MDN The documentation on Core Data for the iPhone has lead to some confusion about how best to use Core Data on a Cocoa Touch device. One particular section seems to be the most confusing, specifically: A view controller typically shouldn’t retrieve the context from a global object such [...]]]></description>
			<content:encoded><![CDATA[<p><strong>This article is reprinted from the MDN</strong></p>

<p>The documentation on Core Data for the iPhone has lead to some confusion about how best to use Core Data on a Cocoa Touch device.  One particular section seems to be the most confusing, specifically:</p>

<blockquote>
  <p>A view controller typically shouldn’t retrieve the context from a global object such as the application delegate. This tends to make the application architecture rigid. Neither should a view controller typically create a context for its own use. This may mean that operations performed using the controller’s context aren’t registered with other contexts, so different view controllers will have different perspectives on the data.</p>
  
  <p>When you create a view controller, you pass it a context. You pass an existing context, or (in a situation where you want the new controller to manage a discrete set of edits) a new context that you create for it. It’s typically the responsibility of the application delegate to create a context to pass to the first view controller that’s displayed.</p>
</blockquote>

<p>The idea behind this section is the issue of rigidity.  Ideally, each view controller should be an island on its own.  It should not rely on its parent, nor should it rely on the Application Delegate.  Once a view controller is pushed onto the screen it should ideally be its own master.</p>

<h2>Why Rigidity is bad</h2>

<p>It is fairly common when designing a Cocoa Touch application to &#8220;hard code&#8221; everything.  Take the following navigation controller design:</p>

<p><img src="http://www.cimgf.com/wp-content/uploads/2011/01/Image1.png" alt="Navigation Controller Design" title="Standard Navigation Controller Design" /></p>

<p>When this design, it is common to code each view controller and make it &#8220;aware&#8221; of its parent.  In that design, it would be common to see view controller B call methods or call back (to its delegate) view controller A.  While there is nothing technically wrong with this design, it is very rigid.  It is nearly impossible to either move view controller B to another location in the stack or to reuse view controller B somewhere else.  This is the trap that the documentation is trying to help new developers avoid.</p>

<h2>Solution One</h2>

<p>Again using a standard/normal navigation controller design, it is expected that the detail flows from left to right.  The left most (or root) view controller contains the most vague information and the right most (or deepest) view controller contains the greatest detail.</p>

<p><img src="http://www.cimgf.com/wp-content/uploads/2011/01/Image2.png" alt="UIFetchedResultsController" title="UIFetchedResultsController" /></p>

<p>In this case then the best solution is to use a <code>UIFetchedResultsController</code>.  This controller can be considered a thin layer between the view controllers and the Core Data bits.  The advantage is that the <code>UIFetchedResultsController</code> is designed to work with tables.  The other advantage is that your least detailed view (the root most likely) can listen as the delegate of the <code>UIFetchedResultsController</code> for changes and update itself.</p>

<p>In this design, however, instead of passing around a context, you would hand off just the entity that the child view controller needs to know about.  The Core Data Recipes example provided by Apple illustrates this design quite well.</p>

<p>How does this break rigidity?  Each view controller, from the root on down, only knows what is passed into it.  The root gets the <code>UIFetchedResultsController</code> passed into it.  The child views only get the items it cares about passed into it.  None of them care what their parent view controller is.  There is no call back to a parent.</p>

<h2>Solution two</h2>

<p>What happens when we don&#8217;t have a typical navigation controller design?  Perhaps a child view can pop up a modal view that displays different information.  Perhaps a child view, for whatever reason needs to access information that cannot be directly passed into it every time.</p>

<p>In these cases there are a few different options.</p>

<h3>View already has a <code>NSManagedObject</code></h3>

<p>Following our example above, lets say that view controller C needs to create a new object.  Perhaps it is a detail view of a recipe and the user wants to add a new recipe type (perhaps she is a vegan and just discovered there is no vegan type in the list).  In this case we have passed in an entity (the recipe) but not a reference to the <code>NSManagedObjectContext</code>.  Fortunately this solution is easy to fix.  The <code>NSManagedObject</code> retains a reference to its <code>NSManagedObjectContext</code> internally and we can access it.  Therefore we can easily retrieve the <code>NSManagedObjectContext</code> from the <code>NSManagedObject</code> and create the new Type entity and pass it to the modal child or whatever our design calls for.</p>

<p>This again avoids rigidity because the view controller that represents the entity does not need to call up to a parent object or the <code>UIApplication</code> delegate.  It is self contained and only manages view controllers that are down stream from it.</p>

<h3>View does not have a <code>NSManagedObject</code></h3>

<p>In this situation things are <em>slightly</em> more complicated.  In this case we want to create a <code>@property</code> for the <code>NSManagedObjectContext</code> and require that our creator set the property.</p>

<pre><code>@interface MyViewController : ViewController
{
    NSManagedObjectContext *moc;
}

@property (nonatomic, retain) NSManagedObjectContext *moc;

@end
</code></pre>

<p>Again, the view controller is an island of its own because it does not care where that <code>NSManagedObjectContext</code> came from.  All it knows is that it is required for the view to function.  It does not care of it is a new <code>NSManagedObjectContext</code> specifically created for its use (perhaps for a cancelable edit tree) or if it is the same <code>NSManagedObjectContext</code> that has been passed around since the launch of the application.  All it knows is that it has the elements it needs to perform its function.</p>

<p>By making the <code>NSManagedObjectContext</code> a settable property we can also transplant the view easily.  If, at some point in the project lifecycle, we decide that it makes more sense to have the following design:</p>

<p><img src="http://www.cimgf.com/wp-content/uploads/2011/01/Image3.png" alt="Modal View Controller" title="Modal View Controller" /></p>

<p>Taking from Apple&#8217;s Recipes Application, perhaps we decide that moving from the table view directly to the image of the recipe is more pleasing to the users and that when they want to see how to make it they can &#8220;flip&#8221; the image over and see the detail.</p>

<p>Making this change with each view controller being an island is quite simple.  We just rearrange the views without having to worry too much about breaking the application.</p>

<h2>Solution three</h2>

<p>Up until now we have been looking at just a navigation controller design.  But what about tab bars?  In the situation of a tab bar we again want to avoid rigidity because it is even more common that tabs will get moved around.</p>

<p>The solution to this is to again use a <code>@property</code> for the <code>NSManagedObjectContext</code> and require that the creator set this property before the view is displayed on screen.  If you are creating the tabs in code this is trivial because you are already calling init on the view controller and you can add one more line of code after the init to set the property.</p>

<p>If the user interface is being developed mostly in Interface Builder it is slightly more tricky.  Personally I am not a fan of creating navigation controllers or tab bar controllers in Interface Builder.  However if that is the design then I would recommend referencing the view controllers as properties and passing along the context upon initialization of the application.  It may be possible to do this entirely in Interface Builder but I am not comfortable enough to recommend that as a solution.</p>

<h2>Conclusion</h2>

<p>The overall idea behind this article is to keep each view controller separate from anything up stream or in a different silo.  This will make the design far more flexible in the long run.  Any time that you feel the &#8220;need&#8221; to pass in a parent view controller to a child view controller, reconsider the design.  Consider using a <code>@protocol</code> delegate design or NSNotification calls instead.  Keep each view controller as its own private island.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/01/07/passing-around-a-nsmanagedobjectcontext-on-the-iphone/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>iPhone DevCon 2010</title>
		<link>http://www.cimgf.com/2010/09/29/iphone-devcon-2010/</link>
		<comments>http://www.cimgf.com/2010/09/29/iphone-devcon-2010/#comments</comments>
		<pubDate>Thu, 30 Sep 2010 00:06:54 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Announcement]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1220</guid>
		<description><![CDATA[Just finished with the iPhone Dev Con 2010 in San Diego and it was a very pleasant conference to go to. The organizers definitely have a nice balance and treated the speakers well. I enjoyed the trip and I hope that everyone who attended my sessions got something out of them. As I promised in [...]]]></description>
			<content:encoded><![CDATA[<p>Just finished with the iPhone Dev Con 2010 in San Diego and it was a very pleasant conference to go to.  The organizers definitely have a nice balance and treated the speakers well.  I enjoyed the trip and I hope that everyone who attended my sessions got something out of them.</p>

<p>As I promised in the sessions, here are the slides and sample code.</p>

<ul>
<li><a href="http://cimgf.s3.amazonaws.com/NSFRC_iPhoneDevCon10.pdf">NSFetchedResultsController</a></li>
<li><a href="http://cimgf.s3.amazonaws.com/Import_Export_iPhoneDevCon10.pdf">Importing and Exporting Efficiently</a></li>
<li><a href="http://cimgf.s3.amazonaws.com/Import_Example.zip">Importing Example Code</a></li>
</ul>

<p>And the ZSContextWatcher is located in our <a href="git://github.com/ZarraStudios/ZDS_Shared.git">open source git hub project</a>.</p>

<p>Thank you to all of the attendees for having me and I look forward to seeing everyone at the next conference.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2010/09/29/iphone-devcon-2010/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

