<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>Cocoa Is My Girlfriend &#187; Core Data</title>
	<atom:link href="http://www.cimgf.com/category/core-data/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cimgf.com</link>
	<description>Taglines are for Windows programmers</description>
	<lastBuildDate>Wed, 11 Jan 2012 15:00:37 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<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>

<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>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>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>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>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>Core Data and Encryption</title>
		<link>http://www.cimgf.com/2010/07/15/core-data-and-encryption/</link>
		<comments>http://www.cimgf.com/2010/07/15/core-data-and-encryption/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 21:20:14 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1161</guid>
		<description><![CDATA[Just a quick post to point out a great article written by Nick Harris of NewsGator fame. He has looked into the issues with Core Data and encryption. Core Data and Enterprise iPhone Applications &#8211; Protecting Your Data It has always been a difficult question and fortunately Apple has addressed it for us. Even better, [...]]]></description>
			<content:encoded><![CDATA[<p>Just a quick post to point out a great article written by Nick Harris of <a href="http://www.newsgator.com">NewsGator</a> fame.  He has looked into the issues with Core Data and encryption.</p>

<p><a href="https://nickharris.wordpress.com/2010/07/14/core-data-and-enterprise-iphone-applications-protecting-your-data/">Core Data and Enterprise iPhone Applications &#8211; Protecting Your Data</a></p>

<p>It has always been a difficult question and fortunately Apple has addressed it for us.  Even better, Nick has shared the code so we don&#8217;t even need to try and discover the solution ourselves.</p>

<p>Thanks Nick!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2010/07/15/core-data-and-encryption/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Re-Ordering NSFetchedResultsController</title>
		<link>http://www.cimgf.com/2010/06/05/re-ordering-nsfetchedresultscontroller/</link>
		<comments>http://www.cimgf.com/2010/06/05/re-ordering-nsfetchedresultscontroller/#comments</comments>
		<pubDate>Sat, 05 Jun 2010 23:06:00 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=995</guid>
		<description><![CDATA[So Marcus is the Core Data guy, but I&#8217;ve been working with it a good bit myself lately and was recently faced with having to add re-ordering for a list of entities in a UITableView. The methods I found online for accomplishing this all suggested using an NSMutableArray as the data source for the table [...]]]></description>
			<content:encoded><![CDATA[<p>So Marcus is the Core Data guy, but I&#8217;ve been working with it a good bit myself lately and was recently faced with having to add re-ordering for a list of entities in a UITableView. The methods I found online for accomplishing this all suggested using an NSMutableArray as the data source for the table view. That will work, but I came up with another method, though similar, that achieved what I need without having to switch from using my NSFetchedResultsController as the data source behind the UITableView. In the end, I did use an NSMutableArray, however, I end up using it just to take advantage of its indexing. Read on to see what I mean.
<span id="more-995"></span></p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2010/05/FavoriteThings.zip'>Download the source code for the Favorite Things project.</a></p>

<h2>A Few of My Favorite Things</h2>

<p>My kids have been watching <em>The Sound of Music</em> lately, but that&#8217;s not what made me decide to use a list of favorite things as the premise of my example code (sorry if that just got a Julie Andrews song stuck in your head. For the rest of you who have no idea what I&#8217;m talking about, move along. Nothing to see here). What made me think of it is the fact that your favorite things might need re-ordered from time to time. A list of my favorite things all seem to be Apple products as the example code shows. Yours might be something else. I&#8217;ve added a method at the start of this example app to populate the Core Data database with a list of a few of my favorite things (&#8220;&#9835;&#9835;&#8230;when the dog bites, when the bee stings, when you&#8217;re feeling sad &#9835;&#9835;&#8230; ooops, sorry). I first fetch the list and if it&#8217;s empty I go ahead and populate the Core Data data store. Here is that 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
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
</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>loadFavoriteThingsData;
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>fetchedResultsController fetchedObjects<span style="color: #002200;">&#93;</span> count<span style="color: #002200;">&#93;</span> &gt; <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>
    <span style="color: #a61390;">return</span>;
&nbsp;
  <span style="color: #400080;">NSManagedObject</span> <span style="color: #002200;">*</span>favoriteThing <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSEntityDescription</span> insertNewObjectForEntityForName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;FavoriteThing&quot;</span> inManagedObjectContext<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self managedObjectContext<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;MacBook Pro&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;thingName&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;A powerful computer that will burn your lap.&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;thingDescription&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithInt<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;displayOrder&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  favoriteThing <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSEntityDescription</span> insertNewObjectForEntityForName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;FavoriteThing&quot;</span> inManagedObjectContext<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self managedObjectContext<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;iPad&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;thingName&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;That's a really big iPod!&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;thingDescription&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithInt<span style="color: #002200;">:</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;displayOrder&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  favoriteThing <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSEntityDescription</span> insertNewObjectForEntityForName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;FavoriteThing&quot;</span> inManagedObjectContext<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self managedObjectContext<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;iPhone&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;thingName&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;A computer that thinks it's a phone.&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;thingDescription&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithInt<span style="color: #002200;">:</span><span style="color: #2400d9;">2</span><span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;displayOrder&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  favoriteThing <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSEntityDescription</span> insertNewObjectForEntityForName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;FavoriteThing&quot;</span> inManagedObjectContext<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self managedObjectContext<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;iPod&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;thingName&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Also known as the iPad nano.&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;thingDescription&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithInt<span style="color: #002200;">:</span><span style="color: #2400d9;">3</span><span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;displayOrder&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  favoriteThing <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSEntityDescription</span> insertNewObjectForEntityForName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;FavoriteThing&quot;</span> inManagedObjectContext<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self managedObjectContext<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;WWDC Ticket&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;thingName&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;It sold out in eight days this year, you know?&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;thingDescription&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>favoriteThing setValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithInt<span style="color: #002200;">:</span><span style="color: #2400d9;">4</span><span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;displayOrder&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>managedObjectContext save<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Our Core Data database will now be populated with some initial data so we&#8217;ll have something to see. Here is what the initial screen looks like:</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2010/05/favoritethings.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2010/05/favoritethings-161x300.png" alt="" title="favoritethings" width="161" height="300" class="alignleft size-medium wp-image-1001" /></a></p>

<h2>Display Order Attribute</h2>

<p>In order to implement re-ordering, your entity in your Core Data model will need a displayOrder attribute (you can call it whatever you want, but I&#8217;ve named mine displayOrder). This is an integer that will keep track of your indexes and is the field you will use to sort your results in the fetch request sort descriptor. Here is what the code looks like to fetch the entities using the displayOrder attribute as the sort descriptor:</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
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>NSFetchedResultsController <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>fetchedResultsController
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>fetchedResultsController<span style="color: #002200;">&#41;</span> <span style="color: #a61390;">return</span> fetchedResultsController;
&nbsp;
  <span style="color: #400080;">NSFetchRequest</span> <span style="color: #002200;">*</span>fetchRequest <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>;
  <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;FavoriteThing&quot;</span> 
                           inManagedObjectContext<span style="color: #002200;">:</span>managedObjectContext<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>fetchRequest setEntity<span style="color: #002200;">:</span>entity<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #400080;">NSSortDescriptor</span> <span style="color: #002200;">*</span>sortDescriptor <span style="color: #002200;">=</span> 
              <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSSortDescriptor</span> alloc<span style="color: #002200;">&#93;</span> initWithKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;displayOrder&quot;</span> 
                                          ascending<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>sortDescriptors <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> alloc<span style="color: #002200;">&#93;</span> 
                              initWithObjects<span style="color: #002200;">:</span>sortDescriptor, <span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;  
  <span style="color: #002200;">&#91;</span>fetchRequest setSortDescriptors<span style="color: #002200;">:</span>sortDescriptors<span style="color: #002200;">&#93;</span>;
&nbsp;
  NSFetchedResultsController <span style="color: #002200;">*</span>aFetchedResultsController <span style="color: #002200;">=</span> 
              <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSFetchedResultsController alloc<span style="color: #002200;">&#93;</span> initWithFetchRequest<span style="color: #002200;">:</span>fetchRequest 
                                                  managedObjectContext<span style="color: #002200;">:</span>managedObjectContext
                                                    sectionNameKeyPath<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> cacheName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;ThingsCache&quot;</span><span style="color: #002200;">&#93;</span>;
  aFetchedResultsController.delegate <span style="color: #002200;">=</span> self;
  <span style="color: #002200;">&#91;</span>self setFetchedResultsController<span style="color: #002200;">:</span>aFetchedResultsController<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>aFetchedResultsController release<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>fetchRequest release<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>sortDescriptor release<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>sortDescriptors release<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #a61390;">return</span> fetchedResultsController;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Your Core Data entity that you want to re-order should look something like this in the data model editor in Xcode:</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2010/05/coredatamodel.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2010/05/coredatamodel-300x215.png" alt="" title="coredatamodel" width="300" height="215" class="alignleft size-medium wp-image-1061" /></a></p>

<h2>Favorites Change</h2>

<p>This post is about re-ordering so here is the point. NSFetchedResultsController doesn&#8217;t have a built in way to re-order the results, so load them into an NSMutableArray, rearrange them there, and then re-iterate over the items once sorted setting each of their displayOrder field as you go. Then save the managed object context and you&#8217;re all re-ordered.</p>

<p>The reason we use an NSMutableArray is because we can insert and remove managed object pointers to/from the array without triggering any changes to the data store. When you make changes to the objects themselves the change is reflected immediately&#8211;which is often what we want, but sometimes we don&#8217;t as in this case. In <a href="http://www.amazon.com/Core-Data-Apples-API-Persisting/dp/1934356328/ref=sr_1_1?ie=UTF8&#038;s=books&#038;qid=1273621059&#038;sr=8-1">Marcus&#8217; Core Data book</a> he points out that you can keep KVO messages from being sent when you want to change a managed object&#8217;s attributes by calling <strong>-setPrimitiveValue:forKey</strong>, but it seemed simpler to me to just re-arrange the objects in an array, and then make the change to each of the object&#8217;s displayOrder attribute. Here is the code you use to re-order the results:</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
</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>tableView<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UITableView <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>tableView 
moveRowAtIndexPath<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSIndexPath</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>sourceIndexPath 
      toIndexPath<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSIndexPath</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>destinationIndexPath;
<span style="color: #002200;">&#123;</span>  
  <span style="color: #400080;">NSMutableArray</span> <span style="color: #002200;">*</span>things <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>fetchedResultsController fetchedObjects<span style="color: #002200;">&#93;</span> mutableCopy<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #11740a; font-style: italic;">// Grab the item we're moving.</span>
  <span style="color: #400080;">NSManagedObject</span> <span style="color: #002200;">*</span>thing <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self fetchedResultsController<span style="color: #002200;">&#93;</span> objectAtIndexPath<span style="color: #002200;">:</span>sourceIndexPath<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #11740a; font-style: italic;">// Remove the object we're moving from the array.</span>
  <span style="color: #002200;">&#91;</span>things removeObject<span style="color: #002200;">:</span>thing<span style="color: #002200;">&#93;</span>;
  <span style="color: #11740a; font-style: italic;">// Now re-insert it at the destination.</span>
  <span style="color: #002200;">&#91;</span>things insertObject<span style="color: #002200;">:</span>thing atIndex<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>destinationIndexPath row<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #11740a; font-style: italic;">// All of the objects are now in their correct order. Update each</span>
  <span style="color: #11740a; font-style: italic;">// object's displayOrder field by iterating through the array.</span>
  <span style="color: #a61390;">int</span> i <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>;
  <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObject</span> <span style="color: #002200;">*</span>mo <span style="color: #a61390;">in</span> things<span style="color: #002200;">&#41;</span>
  <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>mo setValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithInt<span style="color: #002200;">:</span>i<span style="color: #002200;">++</span><span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;displayOrder&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
&nbsp;
  <span style="color: #002200;">&#91;</span>things release<span style="color: #002200;">&#93;</span>, things <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>managedObjectContext save<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<h2>Further Considerations</h2>

<p>You may be thinking that if you iterate through every object in your results you&#8217;re actually loading them into memory. This is true, but not something to be concerned about for a couple reasons. First, the results were loaded into memory to display in the table view already. Also, in any table view where you are planning to re-order your results, it is highly unlikely that your list of objects will be very long as trying to re-order too many objects would just prove frustrating for your user and your design has just clearly demonstrated the need to be re-designed at that point anyhow.</p>

<h2>Finishing Up</h2>

<p>There are just a few more points I want to make before we&#8217;re done.</p>

<p>The project template I used is just the default navigation template along with Core Data for storage.</p>

<p>In order for the table view to display the detail text, you need to instantiate your UITableViewCells using the UITableViewCellStyleSubtitle constant. Here is the code to do so:</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;">static</span> <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>CellIdentifier <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Cell&quot;</span>;
&nbsp;
UITableViewCell <span style="color: #002200;">*</span>cell <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>tableView dequeueReusableCellWithIdentifier<span style="color: #002200;">:</span>CellIdentifier<span style="color: #002200;">&#93;</span>;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>cell <span style="color: #002200;">==</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
  cell <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UITableViewCell alloc<span style="color: #002200;">&#93;</span> initWithStyle<span style="color: #002200;">:</span>UITableViewCellStyleSubtitle 
                                 reuseIdentifier<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Cell&quot;</span><span style="color: #002200;">&#93;</span> autorelease<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Finally, remember that you have to implement <strong>-canMoveRowAtIndexPath</strong> and return YES if you want the re-order control to display:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</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;">BOOL</span><span style="color: #002200;">&#41;</span>tableView<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UITableView <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>tableView canMoveRowAtIndexPath<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSIndexPath</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>indexPath
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">return</span> <span style="color: #a61390;">YES</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<h2>Conclusion</h2>

<p>The <strong>NSFetchedResulsController</strong> in tandem with a simple <strong>NSMutableArray</strong> works great to provide re-ordering for your table views. Until next time.</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2010/05/FavoriteThings.zip'>Download the source code for the Favorite Things project.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2010/06/05/re-ordering-nsfetchedresultscontroller/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Creating a NSManagedObject that is Cross Platform</title>
		<link>http://www.cimgf.com/2010/02/18/creating-a-nsmanagedobject-that-is-cross-platform/</link>
		<comments>http://www.cimgf.com/2010/02/18/creating-a-nsmanagedobject-that-is-cross-platform/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 18:37:33 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=950</guid>
		<description><![CDATA[An interesting question came up on Stackoverflow today so I decided to expound upon it in a short blog post. A situation that I believe we are going to be seeing more and more often is one where application developers are writing multiple &#8220;versions&#8221; of their applications to be used on the desktop, their iPhone [...]]]></description>
			<content:encoded><![CDATA[<p>An interesting question came up on Stackoverflow today so I decided to expound upon it in a short blog post.</p>

<p>A situation that I believe we are going to be seeing more and more often is one where application developers are writing multiple &#8220;versions&#8221; of their applications to be used on the desktop, their iPhone and now the iPad.</p>

<p>Because of that situation, it is becoming even more important that we write as much portable code as possible.  Fortunately, our model can be completely portable between the two platforms.</p>

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

<h2>NSImage vs UIImage</h2>

<p>The primary issue with creating a portable model and model objects is images.  Now, if the images are stored on disk and only referenced in your Core Data model, then you don&#8217;t have an issue.  Since you are storing the images on disk in a portable format (png, jpeg, etc.) then they will port right over to all of the platforms you are targeting.</p>

<p>But what happens when you are working with small images that should be stored within Core Data?  Simple right, just use a transformable data type and stick the image right in there.</p>

<p>Unfortunately that fails in the portability department.</p>

<p>The issue is that on the desktop you are storing a serialized version of the NSImage instance and on the other devices you are storing an instance of UIImage.  Two different data structures that are incompatible.  So what is the right answer?</p>

<p>Store the images in a portable format even in Core Data.</p>

<p>But that is hard right?</p>

<p>Fortunately if we create concrete subclasses of any entity that needs to store images it is a small amount of code and some conditional compiling.</p>

<h3><code>MyEntityWithAnImage.h</code></h3>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;">&nbsp;
<span style="color: #a61390;">@interface</span> MyEntityWithAnImage <span style="color: #002200;">:</span> <span style="color: #400080;">NSManagedObject</span>
<span style="color: #002200;">&#123;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#ifdef IPHONEOS_DEPLOYMENT_TARGET</span>
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> UIImage <span style="color: #002200;">*</span>image;
<span style="color: #6e371a;">#else</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;">NSImage</span> <span style="color: #002200;">*</span>image;
<span style="color: #6e371a;">#endif</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>


<p>In the header we declare the same property and the use some conditional compiling to determine which definition should be used.  On the desktop the property image will return an NSImage and on the other platforms it will return a UIImage.  But how do we work this magic?</p>

<h3><code>MyEntityWithAnImage.m</code></h3>


<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: #6e371a;">#ifdef IPHONEOS_DEPLOYMENT_TARGET</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>setImage<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIImage<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>self willChangeValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>data <span style="color: #002200;">=</span> UIImagePNGRepresentation<span style="color: #002200;">&#40;</span>image<span style="color: #002200;">&#41;</span>;
  <span style="color: #002200;">&#91;</span>myManagedObject setImage<span style="color: #002200;">:</span>data<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self setPrimitiveValue<span style="color: #002200;">:</span>data forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self didChangeValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>UIImage<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>self willAccessValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  UIImage <span style="color: #002200;">*</span>image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIImage imageWithData<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self primitiveValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self didAccessValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">return</span> image;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#else</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>setImage<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSImage</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>self willChangeValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #400080;">NSBitmapImageRep</span> <span style="color: #002200;">*</span>bits <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>image representations<span style="color: #002200;">&#93;</span> objectAtIndex<span style="color: #002200;">:</span> <span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>data <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>bits representationUsingType<span style="color: #002200;">:</span>NSPNGFileType properties<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>myManagedObject setImage<span style="color: #002200;">:</span>data<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self setPrimitiveValue<span style="color: #002200;">:</span>data forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self didChangeValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><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;">NSImage</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>self willAccessValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #400080;">NSImage</span> <span style="color: #002200;">*</span>image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSImage</span> alloc<span style="color: #002200;">&#93;</span> initWithData<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self primitiveValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self didAccessValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>image autorelease<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#endif</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>


<p>Here we are overriding the dynamic accessors and implementing our own.  We are fully KVO compliant and notify when we are accessing or changing the image value.</p>

<p>In the desktop version we grab the bitmap image representation and then get the PNG representation of it and store that representation into Core Data as NSData.</p>

<p>In the Cocoa Touch version we are using the C function which returns the PNG representation of the UIImage instance directly.  We are again storing that as NSData into our image property.</p>

<p>In both cases the getter reverses the process by loading the NSData back into the appropriate image instance.</p>

<h2>Wrap Up</h2>

<p>This makes the code external to our <code>NSManagedObject</code> completely unaware of the actual data storage and they just know that they are getting back the object they need to work with.</p>

<p>BTW, if anyone knows of another pre-processor variable that I should be using for this instead of <code>IPHONEOS_DEPLOYMENT_TARGET</code> please let me know.  I am not 100% confident that <code>IPHONEOS_DEPLOYMENT_TARGET</code> is the best variable to be testing against.</p>

<p>Do you like this idea, hate it?  Tell me in person at <a href='http://nsconference.com/'>NSConferenceUSA</a>!  Tickets are still available and it will be great to see you there.</p>

<p>If that is too soon then please catch me at <a href='http://360idev-MarcusZ.eventbrite.com/'>360 iDev</a> in April!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2010/02/18/creating-a-nsmanagedobject-that-is-cross-platform/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>The PragPub Magazine</title>
		<link>http://www.cimgf.com/2010/01/09/the-pragpub-magazine/</link>
		<comments>http://www.cimgf.com/2010/01/09/the-pragpub-magazine/#comments</comments>
		<pubDate>Sat, 09 Jan 2010 16:21:59 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=859</guid>
		<description><![CDATA[Last month I was given the opportunity to write an article for The Pragmatic Programmers great magazine called &#8220;PragPub&#8221;. I am happy to say that the article I wrote for them was published in this month&#8217;s edition. The article, titled &#8220;Touching the Core&#8221;, is a walk through Apple&#8217;s great addition to the Core Data API [...]]]></description>
			<content:encoded><![CDATA[<p>Last month I was given the opportunity to write an article for The Pragmatic Programmers great magazine called &#8220;PragPub&#8221;.  I am happy to say that the article I wrote for them was published in this month&#8217;s edition.  The article, titled &#8220;Touching the Core&#8221;, is a walk through Apple&#8217;s great addition to the Core Data API for the iPhone.</p>

<p>Specifically this article walks through using the NSFetchedResultsController and some best practices in its use.  The magazine is available for free on their website, <a href="http://pragprog.com/magazines">The Pragmatic Bookshelf</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2010/01/09/the-pragpub-magazine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding iTunes-style search to your Core Data application</title>
		<link>http://www.cimgf.com/2008/11/25/adding-itunes-style-search-to-your-core-data-application/</link>
		<comments>http://www.cimgf.com/2008/11/25/adding-itunes-style-search-to-your-core-data-application/#comments</comments>
		<pubDate>Tue, 25 Nov 2008 20:14:09 +0000</pubDate>
		<dc:creator>Fraser Hess</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=381</guid>
		<description><![CDATA[iTunes has a very neat way of searching your library, where it takes each word in your search and tries to find that word in multiple fields.Â For example, you can search for &#8220;yesterday beatles&#8221; and it will match &#8220;yesterday&#8221; in the Name field and &#8220;beatles&#8221; in the Artist field. The basic predicate binding for [...]]]></description>
			<content:encoded><![CDATA[<p>iTunes has a very neat way of searching your library, where it takes each word in your search and tries to find that word in multiple fields.Â  For example, you can search for &#8220;yesterday beatles&#8221; and it will match &#8220;yesterday&#8221; in the Name field and &#8220;beatles&#8221; in the Artist field. The basic predicate binding for NSSearchField provided by Interface Builder is not complex enough to archive this kind of search.Â  I need to build the predicate dynamically since I can&#8217;t assume what field the user is trying to search and that each additional word should filter the list further &#8211; just like iTunes.Â  Here is how to go about adding iTunes-style searching.
<span id="more-381"></span>
In my application I have a simple Core Data model with one entity (song) and 3 attributes (name, album and artist).</p>

<p>Add the following to iTunesFilter_AppDelegate.h:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">IBOutlet <span style="color: #400080;">NSSearchField</span> <span style="color: #002200;">*</span>searchField;
IBOutlet <span style="color: #400080;">NSArrayController</span> <span style="color: #002200;">*</span>songArrayController;</pre></div></div>


<p>and</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>IBAction<span style="color: #002200;">&#41;</span>filterSongs<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender;</pre></div></div>


<p>With those changes I can go into Interface Builder and wire up the NSSearchField to searchField and my NSArrayController to songArrayController.Â  I also make the action of the NSSearchField, filterSongs:.</p>

<p>I have one more change and that is to make the Action of the NSSearchField &#8220;Sent on End Editing&#8221;</p>

<p>All we need now is to add the code for -filterSongs to iTunesFilter_AppDelegate.m:</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
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>filterSongs<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender <span style="color: #002200;">&#123;</span>
<span style="color: #400080;">NSMutableString</span> <span style="color: #002200;">*</span>searchText <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableString</span> stringWithString<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>searchField stringValue<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Remove extraenous whitespace</span>
<span style="color: #a61390;">while</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>searchText rangeOfString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Â  &quot;</span><span style="color: #002200;">&#93;</span>.location <span style="color: #002200;">!=</span> NSNotFound<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>searchText replaceOccurrencesOfString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Â  &quot;</span> withString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot; &quot;</span> options<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> range<span style="color: #002200;">:</span>NSMakeRange<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #002200;">&#91;</span>searchText length<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">//Remove leading space</span>
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>searchText length<span style="color: #002200;">&#93;</span> <span style="color: #002200;">!=</span> <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#91;</span>searchText replaceOccurrencesOfString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot; &quot;</span> withString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;&quot;</span> options<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> range<span style="color: #002200;">:</span>NSMakeRange<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>,<span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">//Remove trailing space</span>
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>searchText length<span style="color: #002200;">&#93;</span> <span style="color: #002200;">!=</span> <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#91;</span>searchText replaceOccurrencesOfString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot; &quot;</span> withString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;&quot;</span> options<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> range<span style="color: #002200;">:</span>NSMakeRange<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>searchText length<span style="color: #002200;">&#93;</span><span style="color: #002200;">-</span><span style="color: #2400d9;">1</span>, <span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>searchText length<span style="color: #002200;">&#93;</span> <span style="color: #002200;">==</span> <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>songArrayController setFilterPredicate<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">return</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>searchTerms <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>searchText componentsSeparatedByString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot; &quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>searchTerms count<span style="color: #002200;">&#93;</span> <span style="color: #002200;">==</span> <span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSPredicate</span> <span style="color: #002200;">*</span>p <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;(name contains[cd] %@) OR (album contains[cd] %@) OR (artist contains[cd] %@)&quot;</span>, searchText, searchText, searchText<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>songArrayController setFilterPredicate<span style="color: #002200;">:</span>p<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSMutableArray</span> <span style="color: #002200;">*</span>subPredicates <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableArray</span> alloc<span style="color: #002200;">&#93;</span> init<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>term <span style="color: #a61390;">in</span> searchTerms<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #400080;">NSPredicate</span> <span style="color: #002200;">*</span>p <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;(name contains[cd] %@) OR (album contains[cd] %@) OR (artist contains[cd] %@)&quot;</span>, term, term, term<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span>subPredicates addObject<span style="color: #002200;">:</span>p<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #400080;">NSPredicate</span> <span style="color: #002200;">*</span>cp <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSCompoundPredicate</span> andPredicateWithSubpredicates<span style="color: #002200;">:</span>subPredicates<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span>songArrayController setFilterPredicate<span style="color: #002200;">:</span>cp<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Here&#8217;s how it works:
After we remove extra whitespace in the string, we breakdown the string into each word (-componentsSeparatedByString:).Â  Then we build an NSPredicate for each word in the string, before the real magic happens by combining these together using NSCompoundPredicate andPredicateWithSubpredicates:</p>

<p>In the end I get a predicate that looks like this:
((name contains[cd] yesterday) or (artist contains[cd] yesterday) or (album contains[cd] yesterday)) and ((name contains[cd] beatles) or (artist contains[cd] beatles) or (album contains[cd] beatles))</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2008/11/itunesfilter.zip'>iTunesFilter Sample Application</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/11/25/adding-itunes-style-search-to-your-core-data-application/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Announcement: Marcus&#8217; Core Data Book Just Went Beta!</title>
		<link>http://www.cimgf.com/2008/10/27/announcement-marcus-core-data-book-just-went-beta/</link>
		<comments>http://www.cimgf.com/2008/10/27/announcement-marcus-core-data-book-just-went-beta/#comments</comments>
		<pubDate>Mon, 27 Oct 2008 18:23:12 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Announcement]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=335</guid>
		<description><![CDATA[A lot of hard work has gone into this book already and I see it becoming the definitive text on the subject of Core Data. The release date is slated for March 30, 2009, but it&#8217;s great to see it in beta. If you want to pick up the beta in PDF, it is available [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.cimgf.com/wp-content/uploads/2008/10/mzcd.jpg" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2008/10/mzcd.jpg" alt="Core Data Book" title="Core Data Book" width="190" height="228" class="size-full wp-image-338" align='left' /></a>A lot of hard work has gone into this book already and I see it becoming the definitive text on the subject of Core Data. The release date is slated for March 30, 2009, but it&#8217;s great to see it in beta. If you want to pick up the beta in PDF, it <strong>is available now from Pragmatic here:</strong> <a href="http://www.pragprog.com/titles/mzcd/core-data">Core Data: Apple&#8217;s API for Persisting Data under Mac OS X</a>.</p>

<p>While new Cocoa programmers will find it a great help to getting started quickly with Core Data, the book also covers some really interesting and advanced topics such as data versioning and migration, Spotlight/Quick Look integration, Sync Services, and multi-threading. You can really see Marcus&#8217; command of the subject shine in these chapters which are already available in the beta.</p>

<p>Give Marcus some feedback on the book as it progresses. It&#8217;s going to be a great reference for any Cocoa Developer looking to harness the power of Core Data.</p>

<p>$21.00 for the beta PDF
$41.35 for the beta PDF plus hard copy when it&#8217;s released in March.</p>

<p>Mad props to Marcus. Congratulations!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/10/27/announcement-marcus-core-data-book-just-went-beta/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Cocoa Tutorial: Wiring Undo Management Into Core Data</title>
		<link>http://www.cimgf.com/2008/04/30/cocoa-tutorial-wiring-undo-management-into-core-data/</link>
		<comments>http://www.cimgf.com/2008/04/30/cocoa-tutorial-wiring-undo-management-into-core-data/#comments</comments>
		<pubDate>Wed, 30 Apr 2008 17:46:55 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=115</guid>
		<description><![CDATA[Undo support in Cocoa is fantastic but for those who have tried to mix it with Core Data know that it can be a bit frustrating. Generally, undo support can be ignored in most applications and it will &#8220;just work&#8221;. But when Core Data is added to the recipe then things get a bit confusing [...]]]></description>
			<content:encoded><![CDATA[<p>Undo support in Cocoa is fantastic but for those who have tried to mix it with Core Data know that it can be a bit frustrating.  Generally, undo support can be ignored in most applications and it will &#8220;just work&#8221;.  But when Core Data is added to the recipe then things get a bit confusing and more complicated.</p>

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

<h3>The Conflict With NSUndoManager</h3>

<p>For those familiar with the inner workings of Cocoa&#8217;s undo support (and if you are not familiar with it, check out the <a href="http://www.mactech.com/articles/mactech-synopses/304900-24.04-Grokking-Synopsis.html">April edition of MacTech ;-) </a>, all of the undo events are registered with an NSUndoManager.  In a normal document model application, the window controller (or the window&#8217;s delegate if set to something other than the controller) will supply an NSUndoManager for all of the text fields and other editable bits in the window.  </p>

<p>This works fine until Core Data comes along.  The reason for this is that the NSManagedObjectContext has its own NSUndoManager that is registering those same events and can easily get out of sync.  </p>

<p>What I prefer to do is avoid the double NSUndoManager and just use the one included with the NSManagedObjectContext.  This can be done by implementing one of the window delegate methods:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</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: #400080;">NSUndoManager</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>windowWillReturnUndoManager<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSWindow</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>window
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>self undoManager<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;">NSUndoManager</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>undoManager
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self managedObjectContext<span style="color: #002200;">&#93;</span> undoManager<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>By utilizing the NSUndoManager that is included in the context, some very powerful features are enabled.</p>

<h3>Grouping sheet modifications</h3>

<p>A common UI design is to allow the editing of an object in a sheet.  The user double clicks on the item or otherwise indicates that they want to edit it and a sheet drops down allowing them to change the values.  Naturally, that sheet has an NSUndoManager attached to it (can even use the one from Core Data) and each individual field can be undone.  However, how to do we handle the cancel button or the ability to undo the entire sheet?</p>

<p>Both of the above can be handled with groupings inside of the NSManagedObjectContext object&#8217;s NSUndoManager.  The methods would work as follows:</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
</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>presentEditSheet<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self undoManager<span style="color: #002200;">&#93;</span> beginUndoGrouping<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>NSApp beginSheet<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self editSheet<span style="color: #002200;">&#93;</span> 
     modalForWindow<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self window<span style="color: #002200;">&#93;</span> 
      modalDelegate<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> 
     didEndSelector<span style="color: #002200;">:</span><span style="color: #a61390;">NULL</span> 
        contextInfo<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><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>acceptChanges<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self editSheet<span style="color: #002200;">&#93;</span> orderOut<span style="color: #002200;">:</span>sender<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>NSApp endSheet<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self editSheet<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self undoManager<span style="color: #002200;">&#93;</span> endUndoGrouping<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self undoManager<span style="color: #002200;">&#93;</span> setActionName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Object edit&quot;</span><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>cancelChanges<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self editSheet<span style="color: #002200;">&#93;</span> orderOut<span style="color: #002200;">:</span>sender<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>NSApp endSheet<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self editSheet<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self undoManager<span style="color: #002200;">&#93;</span> endUndoGrouping<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self undoManager<span style="color: #002200;">&#93;</span> undo<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>In this example I have started an undo group before presenting the sheet.  After the sheet is closed I then end the grouping and if the sheet was not cancelled I give the group a name.  This name will display in the menu and allow all of the changes inside of the sheet to be undone in one stroke.  If the sheet is cancelled then the group is still closed but I immediately call undo instead and everything that occurred within the sheet is wiped clean.</p>

<h3>Conclusion</h3>

<p>By only using one NSUndoManager it makes life a lot simplier and gives consistent results to the user.  This technique can also be used in a document model application but each document will have to reference the appropriate NSUndoManager that is associated with its own NSManagedObjectContext.</p>

<h3>Feedback</h3>

<p>If you have some other interesting ways to use the NSUndoManager I would love to hear about them either here in the comments or you can email me directly at marcus at cimgf.com.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/04/30/cocoa-tutorial-wiring-undo-management-into-core-data/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

