<?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; Cocoa</title>
	<atom:link href="http://www.cimgf.com/category/cocoa/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>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>Super Happy Easy Fetching in Core Data</title>
		<link>http://www.cimgf.com/2011/03/13/super-happy-easy-fetching-in-core-data/</link>
		<comments>http://www.cimgf.com/2011/03/13/super-happy-easy-fetching-in-core-data/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 05:30:04 +0000</pubDate>
		<dc:creator>Saul Mora</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[core-data]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1351</guid>
		<description><![CDATA[First up, I want to thank Matt Long and Marcus Zarra for allowing me to guest post on CIMGF. This post is the first in a short series of topics describing how to I&#8217;ve made using Core Data a little simpler without giving up the power features you still need. The full project from which [...]]]></description>
			<content:encoded><![CDATA[<p>First up, I want to thank Matt Long and Marcus Zarra for allowing me to guest post on CIMGF. This post is the first in a short series of topics describing how to I&#8217;ve made using Core Data a little simpler without giving up the power features you still need. The full project from which this series is derived is available on <a href="http://github.com/magicalpanda/activerecord-fetching-for-core-data">github</a>.</p>

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

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

<h2>Easy Fetches</h2>

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


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


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

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

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

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

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

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

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


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


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


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


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


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


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

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


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


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

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


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


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


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


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

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


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


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

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

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

<p>Next time, we&#8217;ll discuss how to handle other common request operations such as filtering, prefetching keys and even returning only one object.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/03/13/super-happy-easy-fetching-in-core-data/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Subduing CATiledLayer</title>
		<link>http://www.cimgf.com/2011/03/01/subduing-catiledlayer/</link>
		<comments>http://www.cimgf.com/2011/03/01/subduing-catiledlayer/#comments</comments>
		<pubDate>Tue, 01 Mar 2011 06:01:15 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1321</guid>
		<description><![CDATA[Many technologies we use as Cocoa/Cocoa Touch developers stand untouched by the faint of heart because often we simply don&#8217;t understand them and employing them can seem a daunting task. One of those technologies is found in Core Animation and is referred to as the CATiledLayer. It seems like a magical sort of technology because [...]]]></description>
			<content:encoded><![CDATA[<p>Many technologies we use as Cocoa/Cocoa Touch developers stand untouched by the faint of heart because often we simply don&#8217;t understand them and employing them can seem a daunting task. One of those technologies is found in Core Animation and is referred to as the CATiledLayer. It seems like a magical sort of technology because so much of its implementation is a bit of a black box and this fact contributes to it being misunderstood. CATiledLayer simply provides a way to draw very large images without incurring a severe memory hit. This is important no matter where you&#8217;re deploying, but it especially matters on iOS devices as memory is precious and when the OS tells you to free up memory, you better be able to do so or your app will be brought down. This blog post is intended to demonstrate that CATiledLayer works as advertised and implementing it is not as hard as it may have once seemed.
<span id="more-1321"></span></p>

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

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

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


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


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


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


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

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

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

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

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


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


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

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

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

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

<h2>Implementing Draw Rect</h2>

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


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


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

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


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


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


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


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

<h2>Conclusion</h2>

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

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

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

<p>When running on the device the image I am tiling is just too large to be tiled completely before the app uses up too much memory and is killed. You will probably want to run in the simulator to see the tiling finish. As noted in the code comments, you un-comment the tiling code and do a first run with the app allowing it to finish tiling. Then, stop the app and re-comment that tiling code and it will just load and display the tiles it created without having to go through that tiling again. I suppose I could have made the tiling code get called in response to a button tap or something like that, but I&#8217;ll leave that as an exercise for the reader. Contact me through the comments below if you have any problems or questions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/03/01/subduing-catiledlayer/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>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>My current Prefix.pch file</title>
		<link>http://www.cimgf.com/2010/05/02/my-current-prefix-pch-file/</link>
		<comments>http://www.cimgf.com/2010/05/02/my-current-prefix-pch-file/#comments</comments>
		<pubDate>Mon, 03 May 2010 00:58:32 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Development Environment]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[``]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=977</guid>
		<description><![CDATA[I have posted and discussed this file a few times but as with all things it has been touched, tweaked, and generally improved upon. In this article we will discuss the latest iteration of my Prefix.pch file. As with anything I post, it is available for you to use as you see fit. The File [...]]]></description>
			<content:encoded><![CDATA[<p>I have posted and discussed this file a few times but as with all things it has been touched, tweaked, and generally improved upon.</p>

<p>In this article we will discuss the latest iteration of my <code>Prefix.pch</code> file.  As with anything I post, it is available for you to use as you see fit.</p>

<h2>The File</h2>

<p>For those who don&#8217;t want to read the entire post, here is the file:</p>


<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;"><span style="color: #6e371a;">#ifdef DEBUG</span>
  <span style="color: #6e371a;">#define DLog(...) NSLog(@&quot;%s %@&quot;, __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__])</span>
  <span style="color: #6e371a;">#define ALog(...) [[NSAssertionHandler currentHandler] handleFailureInFunction:[NSString stringWithCString:__PRETTY_FUNCTION__ encoding:NSUTF8StringEncoding] file:[NSString stringWithCString:__FILE__ encoding:NSUTF8StringEncoding] lineNumber:__LINE__ description:__VA_ARGS__]</span>
<span style="color: #6e371a;">#else</span>
  <span style="color: #6e371a;">#define DLog(...) do { } while (0)</span>
  <span style="color: #6e371a;">#ifndef NS_BLOCK_ASSERTIONS</span>
    <span style="color: #6e371a;">#define NS_BLOCK_ASSERTIONS</span>
  <span style="color: #6e371a;">#endif</span>
  <span style="color: #6e371a;">#define ALog(...) NSLog(@&quot;%s %@&quot;, __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__])</span>
<span style="color: #6e371a;">#endif</span>
&nbsp;
<span style="color: #6e371a;">#define ZAssert(condition, ...) do { if (!(condition)) { ALog(__VA_ARGS__); }} while(0)</span></pre></td></tr></table></div>


<p>This does not <em>replace</em> the Prefix.pch that comes with your project but it does go at the top of every project that I work on.  The rest of this post we will review what this does.
<span id="more-977"></span></p>

<h2><code>#ifdef DEBUG</code></h2>

<p>I normally run my code in one of two modes.  Either I am writing and testing the code or I am compiling it to hand over to QA, a user or Apple (btw I consider all three of those to be synonymous when it comes to builds).  Therefore the first line is a switch to see if we are in debug mode.  I set this value in the build settings of my project.  If you look under the &#8220;Preprocessor Macros&#8221; section you can set the <code>DEBUG</code> definition there.</p>

<h2><code>#define DLog(...)</code></h2>

<p>This is the most used macro I have in my <code>Prefix.pch</code> file.  This is simply <code>NSLog</code> as we know it and love it.  However I automatically prepend the included macro <code>__PRETTY_FUNCTION__</code> so that any log statement that comes out will declare where it is being called from.  Personally I hate having to track down which &#8220;Fix Me&#8221; just spit out to the Console.</p>

<p>The nice thing about <code>DLog</code> over <code>NSLog</code> is that in the other branch this is a no-op that will be removed by the compiler.  Therefore when I do a client build they won&#8217;t see the debug statements nor will their build be slowed down by any potential conditional logic around the debug statements.</p>

<h2><code>#define ALog(...)</code></h2>

<p>While I do not use this one very often I do like this one an awful lot.  When I am in <code>DEBUG</code> mode it will throw an <code>NSAssertion</code> when it gets hit. This is similar to a common line of code that I see:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;">NSAssert<span style="color: #002200;">&#40;</span><span style="color: #a61390;">NO</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;It failed&quot;</span><span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>


<p>or if you want to see the variables:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;">NSAssert2<span style="color: #002200;">&#40;</span><span style="color: #a61390;">NO</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;It failed. Value1: %i Value2: %i&quot;</span>, value1, value2<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>


<p>My version does not have the condition before hand and can take any number of parameters.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;">ALog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;It failed. Value1: %i Value2: %i&quot;</span>, value1, value2<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>


<p>In addition, when the <code>DEBUG</code> flag is not set, this assertion turns into a <code>NSLog</code> which remains visible.  This allows me to have &#8220;This will never happen&#8221; calls in my code that will explode when I hit them but will be more polite if a user hits them but not so polite that I am left wondering what happened.  They won&#8217;t intentionally crash the application but they will leave a fingerprint in the output from the application so that I can discover what happened.</p>

<h2><code>NS_BLOCK_ASSERTIONS</code></h2>

<p>I am of the school of thought that believes you should never throw an assertion in production code.  If your code cannot handle that part of your app being hit and survive in some form or another then it is not production ready.  Simple as that.  Therefore I turn them off in production builds.</p>

<p>However, some other people who write libraries that I depend upon also feel this way.  Therefore I need to check to see if it is already defined so that I can avoid a warning about resetting it.  Since I have warnings set as errors in my code this is needed.</p>

<h2><code>#define ZAssert(condition, ...)</code></h2>

<p>The final gem in this collection is <code>ZAssert</code>.  This is my personal favorite and it lets me clean up my code very nicely.  First, <code>ZAssert</code> is a condition check.  If you pass the check nothing happens.  If you fail the check, bad things happen.  This is just like <code>NSAssert</code> except for one big difference.  When you turn off assertions, <code>NSAssert</code> goes away completely.  This is not what I want to happen in my code.  Instead, when assertions are turned off, I want a failure of this check to turn into an <code>NSLog</code>.  That is what <code>ZAssert</code> does for us.  In this way, we can clean up our code very nicely.  Picture this very common block of code:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>managedObjectContext save<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
  NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;My save failed: %@<span style="color: #2400d9;">\n</span>%@&quot;</span>, <span style="color: #002200;">&#91;</span>error localizedDescription<span style="color: #002200;">&#93;</span>, <span style="color: #002200;">&#91;</span>error userInfo<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
  <span style="color: #a61390;">abort</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>That is a LOT of code just to perform a save!  Blocks of code like this are very common in Objective-C.  Unfortunately we can&#8217;t roll this up into a <code>NSAssert</code> because the entire line of code will disappear when we turn them off.</p>

<p>With <code>ZAssert</code> it gets a lot cleaner:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
ZAssert<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>managedObjectContext save<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;My save failed: %@<span style="color: #2400d9;">\n</span>%@&quot;</span>, <span style="color: #002200;">&#91;</span>error localizedDescription<span style="color: #002200;">&#93;</span>, <span style="color: #002200;">&#91;</span>error userInfo<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>


<p>Because ZAssert survives when <code>NS_BLOCK_ASSERTIONS</code> is set and simply mutates, we can inline the save directly and make the code a lot easier to read.</p>

<h1>Wrap Up</h1>

<p>I am sure this code will evolve.  When it has changed significantly I will do an updated post.  If anyone else has some nice tips for the <code>Prefix.pch</code> then please share them as we all benefit.</p>

<h1>Acknowledgements</h1>

<p>First I would like to recognize Fraser Hess who did the original post and showed me what we can do with macros.</p>

<p>Second I would like to point out that the NSAssert line of code above is borrowed heavily from BareBones software. They figured out how to generate an assertion without actually using the <code>NSAssert</code> macros.</p>

<p><b>Note:</b> The last code block has been corrected as the save was inadvertently being flipped.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2010/05/02/my-current-prefix-pch-file/feed/</wfw:commentRss>
		<slash:comments>17</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>Automatically save the dSYM files.</title>
		<link>http://www.cimgf.com/2009/12/23/automatically-save-the-dsym-files/</link>
		<comments>http://www.cimgf.com/2009/12/23/automatically-save-the-dsym-files/#comments</comments>
		<pubDate>Thu, 24 Dec 2009 02:28:50 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Development Environment]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Version Control]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=843</guid>
		<description><![CDATA[For those not aware, when you compile an Objective-C application, whether it be for the desktop or for Cocoa Touch devices, the debugging symbols are stripped out of the binaries. Therefore, unlike other languages such as Java, when a crash occurs, there is virtually no way to determine where the crash occurred. However, when the [...]]]></description>
			<content:encoded><![CDATA[<p>For those not aware, when you compile an Objective-C application, whether it be for the desktop or for Cocoa Touch devices, the debugging symbols are stripped out of the binaries.  Therefore, unlike other languages such as Java, when a crash occurs, there is virtually no way to determine where the crash occurred.  However, when the applications are compiled, a dSYM bundle is generated.  This bundle allows us to match up the debugging symbols with the application&#8217;s crash log to help determine the cause of the crash.</p>

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

<p>The issue, however, is that the dSYM file must match the binary exactly<sup>[<a name="id394062" href="#ftn.id394062">1</a>]</sup>.  <del>I have not even had luck with pulling the code out of version control and compiling a second time to get the files to match up.</del>  Therefore, we need to store these dSYM files for every build that gets handed off to someone else.  For Cocoa Touch development this means every ad hoc build and every release build.  This can be a pain.  </p>

<p>To solve this problem I wrote a script that is added as the last build phase of all my iPhone projects.  The script will move the dSYM bundle into the project directory in a directory cleverly called &#8220;dSYM&#8221;.  In addition the script will check the bundle into git (after confirming the project is maintained in a git repository) and commit just that bundle.  Also, since the file is always named the same thing, it renames the file using the current date and time so that no two bundles have the same file name.</p>

<h2 id="failure_checks">Failure checks</h2>

<p>The first thing the script does is determine if it should run.</p>

<p><pre><code>if [ "$BUILD_STYLE" == "Debug" ]; then
  echo "Skipping debug"
  exit 0;
fi
</code></pre></p>

<p>The first part of the script checks to see if the build style is Debug.  Since all debug builds run just on the developer&#8217;s device and still contain the debug symbols, they can be safely ignored.</p>

<p><pre><code>if [ "$EFFECTIVE_PLATFORM_NAME" == "-iphonesimulator" ]; then
  echo "Skipping simulator build"
  exit 0;
fi
</code></pre></p>

<p>The second step is to check to see if the build is against the simulator.  Again, we have no interest in storing the symbol files for these builds.</p>

<h2 id="move_the_file">Move the file</h2>

<p>Since the location of the file is determined at build time and can vary from developer to developer (as well as machine to machine) I use the environmental variables that are part of the build.</p>

<p><pre><code>SRC_PATH=${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}
RELATIVE_DEST_PATH=dSYM/${EXECUTABLE_NAME}.$(date +%Y%m%d%H%M%S).app.dSYM
DEST_PATH=${PROJECT_DIR}/${RELATIVE_DEST_PATH}
echo "moving ${SRC_PATH} to ${DEST_PATH}"</p>

<p>mv "${SRC_PATH}" "${DEST_PATH}"
</code></pre></p>

<p>The next step is to build up the paths of where the file is currently and where we are going to move it to.  I like to store these in variables so that I can print them out to the console in case something goes wrong.  </p>

<h2 id="commit_it_to_version_control">Commit it to version control</h2>

<p>Every project is part of version control right? (<em>RIGHT</em>?)</p>

<p><pre><code>if [ -f ".git/config" ]; then
  git add "${RELATIVE_DEST_PATH}"
  git commit -m "Added dSYM file for ${BUILD_STYLE} build" \
      "${RELATIVE_DEST_PATH}"
fi
</code></pre></p>

<p>The final part only occurs if the project is part of a git repository.  If it is then the bundle is added to git and then just that bundle is committed with a simple message.</p>

<h2 id="conclusion">Conclusion</h2>

<p>Although I have recently been having issues getting <code>symbolicatecrash</code> to work properly, eventually either I or someone else will get it working again and at that time these files will be invaluable in tracking down crashes.</p>

<p>The final script is attached.  I normally add the file to the project and then have a script phase that just calls this script file.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2009/12/Move_dSYM_To_Storage.sh.zip" title="Move_dSYM_To_Storage.sh.zip">Move_dSYM_To_Storage.sh.zip</a></p>

<div class="footnote"><p>
<sup>[<a name="ftn.id394062" href="#id394062">1</a>]</sup>Mach-o objects have an embedded uuid which must match the uuid of the dsym files. That&#8217;s why recompiling doesn&#8217;t work. &#8211;<a href='http://twitter.com/iamleeg/status/6998511425'>Graham Lee</a></p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2009/12/23/automatically-save-the-dsym-files/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Limiting 64-bit to 10.6</title>
		<link>http://www.cimgf.com/2009/10/31/limiting-64-bit-to-10-6/</link>
		<comments>http://www.cimgf.com/2009/10/31/limiting-64-bit-to-10-6/#comments</comments>
		<pubDate>Sun, 01 Nov 2009 04:04:22 +0000</pubDate>
		<dc:creator>Fraser Hess</dc:creator>
				<category><![CDATA[Cocoa]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=720</guid>
		<description><![CDATA[Now that we&#8217;re all using XCode 3.2 on Snow Leopard (you are, right?) and building 64-bit apps you may find that not everything 64-bit works when your app is run on Leopard. Loren Brichter of Tweetie fame found that Tweeite launched much more slowly on Leopard and I found that 32-bit web plugins (read Flash) [...]]]></description>
			<content:encoded><![CDATA[<p>Now that we&#8217;re all using XCode 3.2 on Snow Leopard (you are, right?) and building 64-bit apps you may find that not everything 64-bit works when your app is run on Leopard.
<span id="more-720"></span>
Loren Brichter of Tweetie fame found that Tweeite launched much more slowly on Leopard and I found that 32-bit web plugins (read Flash) do not load in a WebView in a 64-bit app in Leopard.</p>

<p>There&#8217;s an Apple approved and supported method for limiting architectures to Mac OS X versions. Here&#8217;s how to limit 32/64-bit Intel apps to only run 64-bit Intel on 10.6.0 and later.</p>

<p>Open your application&#8217;s <strong>Info.plist</strong> in a text editor and add the following before the final <code>&lt;/dict&gt;</code></p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>LSMinimumSystemVersionByArchitecture<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dict<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>x86_64<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>10.6.0<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dict<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></td></tr></table></div>


<p>That&#8217;s it!</p>

<p><a href="http://developer.apple.com/mac/library/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html#//apple_ref/doc/uid/TP40009250-113253-BAJDHACB">Docs for LSMinimumSystemVersionByArchitecture</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2009/10/31/limiting-64-bit-to-10-6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Marching Ants With Core Animation</title>
		<link>http://www.cimgf.com/2009/10/20/marching-ants-with-core-animation/</link>
		<comments>http://www.cimgf.com/2009/10/20/marching-ants-with-core-animation/#comments</comments>
		<pubDate>Tue, 20 Oct 2009 21:13:38 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=789</guid>
		<description><![CDATA[Our Core Animation book should be available by the end of the year. Go ahead and pre-order it now at Amazon if you would like ;-). When we started writing for Addison-Wesley back in September of 2008, I had no idea how long to expect it to take to finish a technical book as this [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.cimgf.com/wp-content/uploads/2009/10/marchingants1.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/10/marchingants1.png" alt="Marching Ants" title="Marching Ants" class="alignleft size-full wp-image-796" width="137" align="left" /></a>Our Core Animation book should be available by the end of the year. Go ahead and <a href="http://www.amazon.com/Core-Animation-Simplified-Techniques-Development/dp/0321617754/ref=sr_1_2?ie=UTF8&#038;s=books&#038;qid=1255981650&#038;sr=8-2">pre-order it now at Amazon</a> if you would like ;-). When we started writing for Addison-Wesley back in September of 2008, I had no idea how long to expect it to take to finish a technical book as this was my first. One thing I discovered though, is that it is when you are about ready to go to production you start to realize all of the things that you probably should have added to the book, but didn&#8217;t think of in time. This blog post will cover one such item as a way to make up for not thinking of it in time. I may include this in a second edition if there is one, but consider this one a freebie.<span id="more-789"></span></p>

<p>One of the Core Animation layers available as of Snow Leopard and iPhone OS 3.0, CAShapeLayer provides some interesting attributes that are animatable. The CAShapeLayer enables you to create a layer that renders any arbitrary shape you specify using a path, a CGPathRef. It also enables you to specify a stroke pattern for the stroke that outlines the shape. A stroke is optional, but if you do specify one you may also determine the pattern for it. I do point this part out in the book in Chapter 10, by the way. You use the method, -setLineDashPattern which takes an NSArray of integers. These integers specify painted segments verses unpainted segments. What this means is that if you specify 10, 5 in your array, for example, you will see 10 units of painted segment and 5 units unpainted. Notice I use the term <em>units</em> as opposed to <em>pixels</em>. This is due to the fact that we are to start getting used to the idea of resolution independence. Pixels don&#8217;t matter in the same way any more.</p>

<p>The pattern example I used is very simple. You could easily specify something much more complex, say 10, 72, 55, 2, 146, etc. for example. This would mean 10 painted units, followed by 72 unpainted units, followed by 55 painted units, followed by 2 unpainted units, followed by 146 painted units&#8211;on and on. You get the picture.</p>

<p>Now for the part I didn&#8217;t mention in the book. You can animate this stroke pattern. If you&#8217;ve ever used any drawing program you realize that when a rectangular area of the image is in a seleted mode, a dashed pattern stroke outlines that area and the pattern will move like marching ants. To achieve this effect manually actually takes quite a bit of effort, but is quite trivial when done with Core Animation.</p>

<p>What makes it so is another little property of the CAShaperLayer called <strong>lineDashPhase</strong>. This property specifies the phase of the stroke pattern. The default is zero. Animate this property to see the marching ants effect. If you want the animation to loop perfectly, set the <strong>toValue</strong> in the animation to the sum of all of the values specified in the lineDashPattern array. The code to animate the lineDashPhase should look something like the following:</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
</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>toggleMarching<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: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>shapeLayer animationForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;linePhase&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
        <span style="color: #002200;">&#91;</span>shapeLayer removeAnimationForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;linePhase&quot;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
        CABasicAnimation <span style="color: #002200;">*</span>dashAnimation;
        dashAnimation <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CABasicAnimation 
                         animationWithKeyPath<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;lineDashPhase&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #002200;">&#91;</span>dashAnimation setFromValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithFloat<span style="color: #002200;">:</span>0.0f<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span>dashAnimation setToValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithFloat<span style="color: #002200;">:</span>15.0f<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span>dashAnimation setDuration<span style="color: #002200;">:</span>0.75f<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span>dashAnimation setRepeatCount<span style="color: #002200;">:</span><span style="color: #2400d9;">10000</span><span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #002200;">&#91;</span>shapeLayer addAnimation<span style="color: #002200;">:</span>dashAnimation forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;linePhase&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>This is the code we would use to animate a stroke pattern of 10, 5. Notice the sum of those two is 15, which is what the call to setToValue takes in the sample code for the animation. This is important. If the phase doesn&#8217;t match the stroke pattern, the animation will jerk back to the starting position. We want the animation to be smooth and seamless.</p>

<p>We set up our CAShaperLayer using the following 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
</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>viewDidLoad <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>super viewDidLoad<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// Create the shape layer</span>
    shapeLayer <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CAShapeLayer layer<span style="color: #002200;">&#93;</span>;
    CGRect shapeRect <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span>0.0f, 0.0f, 200.0f, 100.0f<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setBounds<span style="color: #002200;">:</span>shapeRect<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setPosition<span style="color: #002200;">:</span>CGPointMake<span style="color: #002200;">&#40;</span>160.0f, 140.0f<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setFillColor<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIColor clearColor<span style="color: #002200;">&#93;</span> CGColor<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setStrokeColor<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIColor blackColor<span style="color: #002200;">&#93;</span> CGColor<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setLineWidth<span style="color: #002200;">:</span>1.0f<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setLineJoin<span style="color: #002200;">:</span>kCALineJoinRound<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setLineDashPattern<span style="color: #002200;">:</span>
     <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithObjects<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;">10</span><span style="color: #002200;">&#93;</span>, 
      <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithInt<span style="color: #002200;">:</span><span style="color: #2400d9;">5</span><span style="color: #002200;">&#93;</span>, 
      <span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// Setup the path</span>
    CGMutablePathRef path <span style="color: #002200;">=</span> CGPathCreateMutable<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
    CGPathAddRect<span style="color: #002200;">&#40;</span>path, <span style="color: #a61390;">NULL</span>, shapeRect<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setPath<span style="color: #002200;">:</span>path<span style="color: #002200;">&#93;</span>;
    CGPathRelease<span style="color: #002200;">&#40;</span>path<span style="color: #002200;">&#41;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// Set the layer's contents</span>
    <span style="color: #002200;">&#91;</span>shapeLayer setContents<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIImage imageNamed<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;balloon.jpg&quot;</span><span style="color: #002200;">&#93;</span> CGImage<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self view<span style="color: #002200;">&#93;</span> layer<span style="color: #002200;">&#93;</span> addSublayer<span style="color: #002200;">:</span>shapeLayer<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Set the fill color to clear color so we can see through the shape. Set the line width to 1.0. Set the line join to be rounded. Then create the lineDashPattern. Next we create a path that matches the rectangle of our layer as to outline it correctly.</p>

<p>Finally we set the contents of the shape layer to a CGImageRef of the image we load from the bundle called balloon.jpg.</p>

<p>Once we connect the button in Interface Builder to the action called -toggleMarching, we can start and stop the marching ants animation.</p>

<h2>Conclusion</h2>

<p>The marching ants effect has limited use, but this example code demonstrates once again how Core Animation really simplifies a lot of visual tasks that would have at one time taken a lot more code to achieve. If there is anything I&#8217;ve learned while researching and writing the book it&#8217;s that Core Animation should be the go-to technology for a vast majority of visualizations on OS X and the iPhone. I find many questions related to the visual aspects of programming for both platforms on Stack Overflow have a very elegant answer in Core Animation. Other solutions exist, but they are often much more cumbersome. Until next time.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2009/10/MarchingAnts.zip">Marching Ants Demo Project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2009/10/20/marching-ants-with-core-animation/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>The journey to disabling sleep with IOKit</title>
		<link>http://www.cimgf.com/2009/10/14/the-journey-to-disabling-sleep-with-iokit/</link>
		<comments>http://www.cimgf.com/2009/10/14/the-journey-to-disabling-sleep-with-iokit/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 18:30:42 +0000</pubDate>
		<dc:creator>Fraser Hess</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Rants]]></category>
		<category><![CDATA[Undocumented]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=760</guid>
		<description><![CDATA[If your app is fullscreen, like a game, has a presentation mode, or plays long running movie files, you&#8217;ll want to disable the display from sleeping. DVD Player and Keynote are perhaps the two most obvious examples of this functionality. The documentation for this is a little spotty so here&#8217;s the results of my investigation. [...]]]></description>
			<content:encoded><![CDATA[<p>If your app is fullscreen, like a game, has a presentation mode, or plays long running movie files, you&#8217;ll want to disable the display from sleeping.  DVD Player and Keynote are perhaps the two most obvious examples of this functionality.
<span id="more-760"></span>
The documentation for this is a little spotty so here&#8217;s the results of my investigation.  My initial googling found this snippet from <a href="http://developer.apple.com/mac/library/qa/qa2004/qa1160.html">here</a>.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;">UpdateSystemActivity<span style="color: #002200;">&#40;</span>OverallAct<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>


<p>The docs explain that you fire this every 30 seconds.  On the surface, this looks like a hack and well, I don&#8217;t need a Carbon C call for that, I can fake a mouse event every 30 seconds.</p>

<p>This is out for good anyway, given that it doesn&#8217;t compile on Snow Leopard on x86_64. Carbon 64-bit will never arrive.</p>

<p>Turns out that the modern way to disable sleep uses IOKit. Apple has <a href="http://developer.apple.com/mac/library/qa/qa2004/qa1340.html">a doc</a> for that too. Here is Listing 2:</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
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &lt;IOKit/pwr_mgt/IOPMLib.h&gt;</span>
&nbsp;
...
<span style="color: #11740a; font-style: italic;">// kIOPMAssertionTypeNoDisplaySleep prevents display sleep,</span>
<span style="color: #11740a; font-style: italic;">// kIOPMAssertionTypeNoIdleSleep prevents idle sleep</span>
&nbsp;
IOPMAssertionID assertionID;
IOReturn success <span style="color: #002200;">=</span> IOPMAssertionCreate<span style="color: #002200;">&#40;</span>kIOPMAssertionTypeNoDisplaySleep, 
                                    kIOPMAssertionLevelOn, <span style="color: #002200;">&amp;</span>assertionID<span style="color: #002200;">&#41;</span>; 
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>success <span style="color: #002200;">==</span> kIOReturnSuccess<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
&nbsp;
    <span style="color: #11740a; font-style: italic;">//Add the work you need to do without </span>
    <span style="color: #11740a; font-style: italic;">//  the system sleeping here.</span>
&nbsp;
    success <span style="color: #002200;">=</span> IOPMAssertionRelease<span style="color: #002200;">&#40;</span>assertionID<span style="color: #002200;">&#41;</span>;
    <span style="color: #11740a; font-style: italic;">//The system will be able to sleep again. </span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>With any sample code that I&#8217;m gonna try to use in my apps, I take the time to understand what&#8217;s going on, and to read the docs for that with which I&#8217;m not familiar.  (Don&#8217;t you?  That&#8217;s fine, just throw someone else&#8217;s potential garbage in your app.  I&#8217;m sure it won&#8217;t bite until you least expect it.)</p>

<p>I&#8217;m getting back an <code>IOPMAssertionID</code>, so I proceed to look that up in the XCode documentation viewer. And there&#8217;s nothing to be found. A look in IOPMLib.h tells me it&#8217;s a 32-bit unsigned integer and therefore not very interesting.</p>

<p>So, I move on to look up <code>IOPMAssertionCreate()</code> to find that it was introduced in Leopard only to be deprecated in Snow Leopard in favor of <code>IOPMAssertionCreateWithName()</code>. <code>IOPMAssertionCreateWithName()</code> has an extra parameter over <code>IOPMAssertionCreate()</code>, and it&#8217;s a name as you might imagine. I don&#8217;t care for having deprecated calls in my code so <code>IOPMAssertionCreateWithName()</code> it is. <strong>Caveat</strong>: <code>IOPMAssertionCreateWithName()</code> is not <em>publicly</em> available in Leopard, so either use <code>IOPMAssertionCreate()</code> in Xcode3.1/Leopard or compile in XCode 3.2/Snow Leopard and <code>IOPMAssertionCreateWithName()</code> will work when run on Leopard.</p>

<p>The sample code from Apple lists two assertion types that you can use: <code>kIOPMAssertionTypeNoDisplaySleep</code> that prevents display sleep, and <code>kIOPMAssertionTypeNoIdleSleep</code> that prevents idle sleep.</p>

<p>My testing indicates that <code>kIOPMAssertionTypeNoDisplaySleep</code> actually prevents both display and idle sleep. The intended use case for this is clearly along the lines of playing a movie or running a presentation.</p>

<p><code>kIOPMAssertionTypeNoIdleSleep</code> will still allow the display to sleep, but the Mac never sleeps unless it runs out of battery power.  Use cases for this fall into the category of &#8216;computations that may not finish before the computer sleeps&#8217;, such as bouncing an mixed audio/video file to disk or rendering a 3D image, etc.</p>

<p>Here is an <a href='http://www.cimgf.com/wp-content/uploads/2009/10/DisableSleep.zip'>example project</a> that allows you to test both behaviors. <strong>Note:</strong> The project uses <code>IOPMAssertionCreate()</code> and not <code>IOPMAssertionCreateWithName()</code> in order to compile on both Leopard and Snow Leopard.</p>

<p>In keeping with good practice, I have filed bug reports with Apple for pieces of the documentation that I see as missing.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2009/10/14/the-journey-to-disabling-sleep-with-iokit/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Dropping NSLog in release builds</title>
		<link>http://www.cimgf.com/2009/01/24/dropping-nslog-in-release-builds/</link>
		<comments>http://www.cimgf.com/2009/01/24/dropping-nslog-in-release-builds/#comments</comments>
		<pubDate>Sat, 24 Jan 2009 05:31:57 +0000</pubDate>
		<dc:creator>Fraser Hess</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=411</guid>
		<description><![CDATA[NSLog() is a great tool that helps debugging efforts. Unfortunately it is expensive, especially on the iPhone, and depending on how it&#8217;s used or what you&#8217;re logging, it could leak sensitive or proprietary information. If you look around the web, you&#8217;ll find a few different ways to drop NSLog in your release builds. Here is [...]]]></description>
			<content:encoded><![CDATA[<p>NSLog() is a great tool that helps debugging efforts.  Unfortunately it is expensive, especially on the iPhone, and depending on how it&#8217;s used or what you&#8217;re logging, it could leak sensitive or proprietary information.  If you look around the web, you&#8217;ll find a few different ways to drop NSLog in your release builds.  Here is what I&#8217;ve put together based on those.
<span id="more-411"></span></p>

<p>First add the following to the &lt;AppName&gt;_Prefix.pch file in your Xcode project:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#ifdef DEBUG</span>
<span style="color: #6e371a;">#    define DLog(...) NSLog(__VA_ARGS__)</span>
<span style="color: #6e371a;">#else</span>
<span style="color: #6e371a;">#    define DLog(...) /* */</span>
<span style="color: #6e371a;">#endif</span>
<span style="color: #6e371a;">#define ALog(...) NSLog(__VA_ARGS__)</span></pre></td></tr></table></div>


<p>Right-click on your target and click <strong>Get Info</strong>. Select the <strong>Build</strong> tab. Make sure <strong>Configuration</strong> is set to <strong>Debug</strong>. Add <strong>-DDEBUG</strong> to the <strong>Other C Flags</strong> of your target.</p>

<p>And that&#8217;s about it.  When you want to log only in debug builds use DLog(). In release builds DLog() will be compiled as an empty comment. Otherwise use ALog() for logging in both debug and release builds.  (A as in always.)</p>

<p>I like this approach for a few reasons:</p>

<ol>
    <li>Some approaches comment out all NSLog() statements when compiled.  This approach lets me keep some logging if I want.</li>
    <li>Using ALog() and DLog(), I make a conscious choice about which builds I&#8217;m going to log in.</li>
    <li>There is very little setup.</li>
    <li>There is no overhead.  Because DLog() is defined as NSLog(), executing DLog() is no different than executing NSLog()</li>
</ol>

<p>If you&#8217;d like to replace NSLog with DLog in your source files, here&#8217;s a quick sed command that you can run in Terminal:
<code>$ sed -i ".bak" 's/NSLog/DLog/' *.m</code>
FYI, this will make a backup of each of the .m files whether it changed them or not.</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2009/01/log.zip'>Logging Sample Application</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2009/01/24/dropping-nslog-in-release-builds/feed/</wfw:commentRss>
		<slash:comments>12</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>Landscape Tab Bar Application for the iPhone</title>
		<link>http://www.cimgf.com/2008/11/13/landscape-tab-bar-application-for-the-iphone/</link>
		<comments>http://www.cimgf.com/2008/11/13/landscape-tab-bar-application-for-the-iphone/#comments</comments>
		<pubDate>Fri, 14 Nov 2008 02:53:06 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=361</guid>
		<description><![CDATA[As you develop applications for the iPhone, you will likely use the project templates provided in Xcode. One such template, called &#8220;Tab Bar Application&#8221; helps you get a tab bar application set up quickly, but by default the application it generates only supports portrait mode for display. So how can you make the application also [...]]]></description>
			<content:encoded><![CDATA[<p>As you develop applications for the iPhone, you will likely use the project templates provided in Xcode. One such template, called &#8220;Tab Bar Application&#8221; helps you get a tab bar application set up quickly, but by default the application it generates only supports portrait mode for display. So how can you make the application also support landscape or even only support landscape? In this post we will address that question.
<span id="more-361"></span>
To duplicate the problem, create a new tab bar application in Xcode. To do so,</p>

<ol>
<li>Press Command-Shift-N and select Tab Bar Application in the iPhone OS | Application templates. Click Choose&#8230;</li>
<li>Provide a name for the project. I chose &#8220;Tab Test&#8221;</li>
<li>Click Save</li>
</ol>

<p>The first thing you&#8217;ll notice is that the template has generated two classes for us. One called FirstViewController, which is used to control the first view (ya think?). The other is called Tab_TestAppDelegate which is our application delegate&#8211;the entry point and main controller class for our application.</p>

<p>Take a look at the stub code generated in the FirstViewController. It is commented out for the most part, but you&#8217;ll notice that there is a method in there that gives us what we want for allowing different orientations for our application. In particular, we are interested in <strong>-shouldAutorotateToInterfaceOrientation</strong>. Uncomment that code and have it simply return YES. This setting will enable the controller to support all orientations.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Override to allow orientations other than the default portrait orientation.</span>
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>shouldAutorotateToInterfaceOrientation<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIInterfaceOrientation<span style="color: #002200;">&#41;</span>interfaceOrientation <span style="color: #002200;">&#123;</span>
    <span style="color: #11740a; font-style: italic;">// Return YES for supported orientations</span>
    <span style="color: #a61390;">return</span> <span style="color: #a61390;">YES</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>This <em>should</em> cause our view to change orientation when the device is turned. Build and run the application using the simulator. Once the simulator has loaded the application, select Hardware | Rotate Left. You will notice that while the device did rotate, the view did not. Why is this?</p>

<h2>All Or None</h2>

<p>Remember that the default tab bar application template creates a tab bar component with <strong>two</strong> views. While we have explicitly told the FirstViewController object to allow all orientations, we have not done so with our second view. The way the tab bar controller works is that if <strong>any</strong> of the view controllers have a limitation on the orientation of the view, then <strong>all</strong> views are constrained by the same limitation.</p>

<p>What this means is that all view controllers must override the call to <strong>-shouldAutorotateToInterfaceOrientation</strong> to return the appropriate setting&#8211;YES to allow all. In our default tab bar app, we have not assigned the second view to a controller because we have not defined one, so where is it getting its controller from? Well, the answer is found in interface builder. If you double-click MainWindow.xib in the Resources group of the Xcode project, Interface Builder will load. Click on the tab for the first view in the main window, and then select the Identity tab in the Inspector, you&#8217;ll see what is going on.</p>

<div id="attachment_368" class="wp-caption alignleft" style="width: 310px"><a href="http://www.cimgf.com/wp-content/uploads/2008/11/firstview.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2008/11/firstview-300x245.png" alt="FirstViewController" title="FirstViewController" width="300" height="245" class="size-medium wp-image-368" /></a><p class="wp-caption-text">FirstViewController</p></div>

<p>Notice in the first view <strong>Class</strong> field, it is set to <strong>FirstViewController</strong>. Take a close look now at our second view by clicking the second tab.</p>

<div id="attachment_370" class="wp-caption alignleft" style="width: 310px"><a href="http://www.cimgf.com/wp-content/uploads/2008/11/secondview.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2008/11/secondview-300x245.png" alt="SecondView Controller" title="SecondView Controller" width="300" height="245" class="size-medium wp-image-370" /></a><p class="wp-caption-text">SecondView Controller</p></div>

<p>Notice that the class we&#8217;re using here is the base UIViewController class. This is our view&#8217;s controller. It only provides the base functionality&#8211;which is to say it doesn&#8217;t provide a whole lot. Furthermore it implements the default functionality. The default setting for the orientation of a view controller is portrait only. In other words, only derivative classes are going to be able to override <strong>-shouldAutorotateToInterfaceOrientation</strong> and set it to something other than the default.</p>

<p>If you want your application to be able to support more than the default portrait orientation, all of your tab views must have their own view controller that overrides <strong>-shouldAutorotateToInterfaceOrientation</strong></p>

<h2>Conclusion</h2>

<p>The iPhone is a fun and interesting computing platform. It is very powerful, but it has a lot of nuances that make it fairly different from what you may be used to on OS X. The trick is to remember the principles you&#8217;ve already learned in Cocoa, MVC in particular, and you should be able to deal with the nuances and make them submit to your own will. Until next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/11/13/landscape-tab-bar-application-for-the-iphone/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Core Animation Tutorial: Interrupting Animation Progress</title>
		<link>http://www.cimgf.com/2008/11/05/core-animation-tutorial-interrupting-animation-progress/</link>
		<comments>http://www.cimgf.com/2008/11/05/core-animation-tutorial-interrupting-animation-progress/#comments</comments>
		<pubDate>Thu, 06 Nov 2008 00:10:46 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=317</guid>
		<description><![CDATA[Starting and stopping animations in Core Animation is as simple as adding and removing your animation from the layer upon which is being run. In this post I am going to talk about how to interrupt animation progress and how to determine whether an animation completed its full run or was interrupted. This is accomplished [...]]]></description>
			<content:encoded><![CDATA[<p>Starting and stopping animations in Core Animation is as simple as adding and removing your animation from the layer upon which is being run. In this post I am going to talk about how to interrupt animation progress and how to determine whether an animation completed its full run or was interrupted. This is accomplished with the animation delegate <em>-animationDidStop:finished</em>.
<span id="more-317"></span></p>

<h2>Differentiating Keypath From Key</h2>

<p>Each core animation layer contains a dictionary that enables you to add and remove animations based on a key that you define. I created a layer-backed view that receives mouse clicks and animates the position of the layer toward that mouse click.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</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>mouseDown<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSEvent</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>event;
<span style="color: #002200;">&#123;</span>
    CABasicAnimation <span style="color: #002200;">*</span>animation <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CABasicAnimation animationWithKeyPath<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;position&quot;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>animation setDelegate<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>animation setFromValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSValue</span> valueWithPoint<span style="color: #002200;">:</span>previousValue<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    previousValue <span style="color: #002200;">=</span> NSMakePoint<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>event locationInWindow<span style="color: #002200;">&#93;</span>.x, <span style="color: #002200;">&#91;</span>event locationInWindow<span style="color: #002200;">&#93;</span>.y<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#91;</span>animation setToValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSValue</span> valueWithPoint<span style="color: #002200;">:</span>previousValue<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>animation setDuration<span style="color: #002200;">:</span><span style="color: #2400d9;">2.0</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span>objectLayer addAnimation<span style="color: #002200;">:</span>animation forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;follow&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Notice that when I create the animation, I am creating it with a keypath&#8211;in this case <em>position</em>. The keypath is different from the key by which we store the animation in the animations dictionary contained by the layer. In the sample code I add the animation to the dictionary using a key called &#8220;follow&#8221;. This could be any string that is meaningful to keep track of the animation in question. Consider it a tag.</p>

<p>I only make this distinction because I&#8217;ve seen some confusion about the difference between the two. To summarize, the keypath <em>specifies which layer property you want to animate</em> while the key is <em>the key by which you will store, recall, and delete an animation from the animation dictionary contained by the layer</em>.</p>

<h2>Adding The Animation, Again</h2>

<p>In the code above, you&#8217;ll also notice that we are adding the animation to the layer for the same key each time we receive a <em>-mouseDown</em>. If we are setting a new object in the dictionary each time, then how are we able to keep track of whether or not the animation finished?</p>

<p>By setting a delegate for the animation, we can be notified when animation has been removed from the animations dictionary. We implement the <em>-animationDidStop:finished</em> delegate.</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;">void</span><span style="color: #002200;">&#41;</span>animationDidStop<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CAAnimation <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>theAnimation finished<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>flag
<span style="color: #002200;">&#123;</span>
    NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Animation interrupted: %@&quot;</span>, <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>flag<span style="color: #002200;">&#41;</span>?<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Yes&quot;</span> <span style="color: #002200;">:</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;No&quot;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>There are several things going on here. When we call <em>[objectLayer addAnimation:animation forKey:@"follow"];</em> in our <em>-mouseDown</em> code, the animation that was there previously, if there was one, is replaced by the new one. If the user clicked on the screen before the animation completed, the animation is removed and the delegate <em>-animationDidStop</em> gets called. If instead of clicking the mouse again before the current animation is finished, you just let it finish, the animation is also removed from the dictionary because this is the default behavior for an animation. If you don&#8217;t specify <em>[animation setRemovedOnCompletion:NO]</em> explicitly, the animation will be removed.</p>

<h2>Changing Direction While In Flight</h2>

<p>When the view receives a click the basic animation is re-created and added to the layer for the key &#8220;follow&#8221; again. The fromValue field needs set again, but if you click another spot on the view before the animation finishes, what value do you set it to? If you set it to the previous value, it will simply animate from the previous location which won&#8217;t look right. You want it to change direction rather than starting from the previous start location.</p>

<p>If instead of using a basic animation in our example code we had simply opted to use the animator proxy, calling <em>-setPosition</em> on the layer would do this for us. The problem is that we want to be able to demonstrate the <em>-animationDidStop</em> delegate which we can&#8217;t do with the animator proxy. So how do we provide this functionality of changing direction in flight?</p>

<p>Look no further than the <em>presentationLayer</em> which is accessible through our layer object. We can obtain the last location of our &#8220;position&#8221; parameter by first getting the presentationLayer and getting the position from it instead. We&#8217;ve modified our <em>-mouseDown</em> event to reflect this change.</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
</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>mouseDown<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSEvent</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>event;
<span style="color: #002200;">&#123;</span>
  CABasicAnimation <span style="color: #002200;">*</span>animation <span style="color: #002200;">=</span> 
          <span style="color: #002200;">&#91;</span>CABasicAnimation animationWithKeyPath<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;position&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>animation setDelegate<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #11740a; font-style: italic;">// Get the presentationLayer</span>
  CALayer <span style="color: #002200;">*</span>p <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>CALayer<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span>objectLayer presentationLayer<span style="color: #002200;">&#93;</span>;
  CGPoint position <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>p position<span style="color: #002200;">&#93;</span>;
  <span style="color: #400080;">NSValue</span> <span style="color: #002200;">*</span>prevVal <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSValue</span> valueWithPoint<span style="color: #002200;">:</span>
                      NSPointFromCGPoint<span style="color: #002200;">&#40;</span>position<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>animation setFromValue<span style="color: #002200;">:</span>prevVal<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>animation setToValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSValue</span> valueWithPoint<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>event locationInWindow<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>animation setDuration<span style="color: #002200;">:</span><span style="color: #2400d9;">2.0</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>animation setRemovedOnCompletion<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>objectLayer addAnimation<span style="color: #002200;">:</span>animation forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;follow&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Now, when we click in our view, the animation changes directions from its current location in the animation. The <em>presentationLayer</em> provides you with current values of whatever field you are currently animating. If a value is not being animated, you will get the same value as what is in the main layer.</p>

<h2>Conclusion</h2>

<p>It&#8217;s very handy to have a way to know when an animation is completed. You simply set your app delegate to be your animation&#8217;s delegate and when the animation completes, <em>-animationDidStop:finished</em> gets called conveying through the <em>finished</em> flag whether the animation was interrupted or not. To get our in flight values when the animation hasn&#8217;t completed, we simply look at the <em>presentationLayer</em>. These features of Core Animation are very powerful. Given the choice I would like to see the <em>presentationLayer</em> values become KVO compliant as this would let you monitor changes in real time, but being able to read the current value at any given time is a great capability in its own right. It&#8217;s very cool technology. Until next time.</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2008/11/followme.zip'><img src="http://www.cimgf.com/wp-content/uploads/2008/03/xcode.png" alt="xcode.png" border="0" width="64"/><br />Follow Me Demo Project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/11/05/core-animation-tutorial-interrupting-animation-progress/feed/</wfw:commentRss>
		<slash:comments>3</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>Core Animation Tutorial: Slider Based Layer Rotation</title>
		<link>http://www.cimgf.com/2008/10/25/core-animation-tutorial-slider-based-layer-rotation/</link>
		<comments>http://www.cimgf.com/2008/10/25/core-animation-tutorial-slider-based-layer-rotation/#comments</comments>
		<pubDate>Sun, 26 Oct 2008 00:15:50 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=322</guid>
		<description><![CDATA[It is often helpful to create a custom control for you application that will display a value as a level like a gas gauge shows how full your tank is. In this post I will demonstrate how to create a three layer tree that will show the current rotation of a circular layer as the [...]]]></description>
			<content:encoded><![CDATA[<p>It is often helpful to create a custom control for you application that will display a value as a level like a gas gauge shows how full your tank is. In this post I will demonstrate how to create a three layer tree that will show the current rotation of a circular layer as the value from a slider (NSSlider) is updated in real time. The layers include the root layer, the rotation layer, and a text layer that will display the current rotation in degrees.
<span id="more-322"></span></p>

<h2>The Slider Value</h2>

<p>We connect a slider to an IBAction in xcode that will get called continuously as we have checked the checkbox called &#8216;Continuous&#8217; in Interface Builder. We can read the slider value and apply it to our animation that we use to rotate the layer. In interface builder, we have specified a minimum value of -180, a maximum value of 180 and a current value (our starting value) of 0 on the slide control. When the slider is moved, the rotation updates as does the value of our text layer.</p>

<p>While it is coincidental that the demo application sort of looks like a pumpkin, it seems appropriate considering the time of year.</p>

<div id="attachment_325" class="wp-caption alignleft" style="width: 283px"><a href="http://www.cimgf.com/wp-content/uploads/2008/10/layerrotate.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2008/10/layerrotate-273x300.png" alt="Layer Rotate" title="Layer Rotate" width="273" height="300" class="size-medium wp-image-325" /></a><p class="wp-caption-text">Layer Rotate</p></div>

<h2>Rotation Animation</h2>

<p>Rotating a layer is very simple. You just need to create an animation with &#8220;transform.rotation.z&#8221; as your keypath and then you can set from and to values that the animation will rotate between. We simply keep track of the last value we rotated (<em>previousValue</em> in the code) to and use this as our from value in the next change to the slider.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>CAAnimation<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>rotateAnimation;
<span style="color: #002200;">&#123;</span>
  CABasicAnimation <span style="color: #002200;">*</span> animation;
  animation <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CABasicAnimation 
               animationWithKeyPath<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;transform.rotation.z&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>animation setFromValue<span style="color: #002200;">:</span>DegreesToNumber<span style="color: #002200;">&#40;</span>previousValue<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>animation setToValue<span style="color: #002200;">:</span>DegreesToNumber<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>slider floatValue<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>animation setRemovedOnCompletion<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>animation setFillMode<span style="color: #002200;">:</span>kCAFillModeForwards<span style="color: #002200;">&#93;</span>;
&nbsp;
  previousValue <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>slider floatValue<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #a61390;">return</span> animation;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>When our -sliderChange function gets called when the user moves the slider, we add the animation to the layer again using the key &#8220;rotate&#8221;. This is done first in our -awakeFromNib call and then in the -sliderChange call.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</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>sliderChange<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>degreesTextLayer setString<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%f&quot;</span>, <span style="color: #002200;">&#91;</span>slider floatValue<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>needleLayer addAnimation<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self rotateAnimation<span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;rotate&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>needleLayer setNeedsDisplay<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>You will notice that we call -setNeedsDisplay on the layer. This is necessary as we have implemented the delegate method -drawLayer:inContext. We use this method to draw the vertical and horizontal black lines that intersect in the center of the circle layer.</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
</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>drawLayer<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CALayer <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>layer inContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGContextRef<span style="color: #002200;">&#41;</span>context;
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span> layer <span style="color: #002200;">==</span> needleLayer <span style="color: #002200;">&#41;</span>
  <span style="color: #002200;">&#123;</span>
      CGMutablePathRef path <span style="color: #002200;">=</span> CGPathCreateMutable<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
      CGPathMoveToPoint<span style="color: #002200;">&#40;</span>path,<span style="color: #a61390;">NULL</span>, <span style="color: #002200;">&#91;</span>view bounds<span style="color: #002200;">&#93;</span>.size.width<span style="color: #002200;">/</span><span style="color: #2400d9;">2.0</span>, <span style="color: #2400d9;">0.0</span><span style="color: #002200;">&#41;</span>;
      CGPathAddLineToPoint<span style="color: #002200;">&#40;</span>path, <span style="color: #a61390;">NULL</span>, <span style="color: #002200;">&#91;</span>view bounds<span style="color: #002200;">&#93;</span>.size.width<span style="color: #002200;">/</span><span style="color: #2400d9;">2.0</span>, <span style="color: #002200;">&#91;</span>view bounds<span style="color: #002200;">&#93;</span>.size.height<span style="color: #002200;">&#41;</span>;
&nbsp;
      CGPathMoveToPoint<span style="color: #002200;">&#40;</span>path,<span style="color: #a61390;">NULL</span>, <span style="color: #2400d9;">0.0</span>, <span style="color: #002200;">&#91;</span>view bounds<span style="color: #002200;">&#93;</span>.size.height<span style="color: #002200;">/</span><span style="color: #2400d9;">2.0</span><span style="color: #002200;">&#41;</span>;
      CGPathAddLineToPoint<span style="color: #002200;">&#40;</span>path, <span style="color: #a61390;">NULL</span>, <span style="color: #002200;">&#91;</span>view bounds<span style="color: #002200;">&#93;</span>.size.width, <span style="color: #002200;">&#91;</span>view bounds<span style="color: #002200;">&#93;</span>.size.height<span style="color: #002200;">/</span><span style="color: #2400d9;">2.0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
      CGColorRef black <span style="color: #002200;">=</span>
              CGColorCreateGenericRGB<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0.0</span>, <span style="color: #2400d9;">0.0</span>, <span style="color: #2400d9;">0.0</span>, <span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#41;</span>;
      CGContextSetStrokeColorWithColor<span style="color: #002200;">&#40;</span>context, black<span style="color: #002200;">&#41;</span>;
      CFRelease<span style="color: #002200;">&#40;</span>black<span style="color: #002200;">&#41;</span>;
&nbsp;
      CGContextBeginPath<span style="color: #002200;">&#40;</span>context<span style="color: #002200;">&#41;</span>;
      CGContextAddPath<span style="color: #002200;">&#40;</span>context, path<span style="color: #002200;">&#41;</span>;
&nbsp;
      CGContextSetLineWidth<span style="color: #002200;">&#40;</span>context, <span style="color: #2400d9;">3.0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
      CGContextStrokePath<span style="color: #002200;">&#40;</span>context<span style="color: #002200;">&#41;</span>;
&nbsp;
      CFRelease<span style="color: #002200;">&#40;</span>path<span style="color: #002200;">&#41;</span>;
&nbsp;
  <span style="color: #002200;">&#125;</span>  
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<h2>Retaining The Rotation Position</h2>

<p>There are two parameters of an animation that must be set otherwise the layer transform will just revert back to the original rotation. These two lines of code in our animation creation code ensure that what you see remains <em>sticky</em> when the value is changed.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>animation setRemovedOnCompletion<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>animation setFillMode<span style="color: #002200;">:</span>kCAFillModeForwards<span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>Now, when the slider moves, the vertical and horizontal lines will stay in the correct rotation position. If you comment those two lines of code out in the demo project, you will see that while the rotation layer animates, it jumps right back to its original rotation as soon as the animation completes.</p>

<h2>Conclusion</h2>

<p>You will likely find many uses for this type of control. You could of course control the rotation based upon some other value or control other than a slider, but this code demonstrates how simple it is to rotate a layer based upon user input. Until next time.</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2008/10/layerrotate.zip'><img src="http://www.cimgf.com/wp-content/uploads/2008/03/xcode.png" alt="xcode.png" border="0" width="64"/><br />Layer Rotate Demo Project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/10/25/core-animation-tutorial-slider-based-layer-rotation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Core Animation Tutorial: Core Animation And Quartz Composer (QCCompositionLayer)</title>
		<link>http://www.cimgf.com/2008/09/24/core-animation-tutorial-core-animation-and-quartz-composer-qccompositionlayer/</link>
		<comments>http://www.cimgf.com/2008/09/24/core-animation-tutorial-core-animation-and-quartz-composer-qccompositionlayer/#comments</comments>
		<pubDate>Wed, 24 Sep 2008 16:18:16 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=289</guid>
		<description><![CDATA[Last night at NSCoder night, Fraser Hess was asking question about being able to draw in a Quartz Composer View (QCView) about which none of the rest of us had any knowledge or experience. As I&#8217;ve been doing a lot with Core Animation lately, I asked him if it was possible to just make the [...]]]></description>
			<content:encoded><![CDATA[<p>Last night at NSCoder night, Fraser Hess was asking question about being able to draw in a Quartz Composer View (QCView) about which none of the rest of us had any knowledge or experience. As I&#8217;ve been doing a lot with Core Animation lately, I asked him if it was possible to just make the view layer backed and start adding layers to it. Fraser hasn&#8217;t worked with Core Animation much yet, so he was unsure. The other three of us set to looking at docs and making demo apps. The race was on&#8230; Oh. It&#8217;s not a race? Sorry about that. I thought we were practicing for Iron Coder&#8230;
<span id="more-289"></span>
My first attempt to get a QCView working succeeded. I was able to display a Quartz Composition in a window, but then I decided to try to make the QCView layer-backed like this:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>window contentView<span style="color: #002200;">&#93;</span> setWantsLayer<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>qcView setWantsLayer<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
&nbsp;
CATextLayer <span style="color: #002200;">*</span>text <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CATextLayer layer<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>text setString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;hello World&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>text setFrame<span style="color: #002200;">:</span>NSRectToCGRect<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>qcView frame<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>qcView layer<span style="color: #002200;">&#93;</span> addSublayer<span style="color: #002200;">:</span>text<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>This code would allow the text layer to show up, however, the Quartz Composition was gone and all I got was a gray window with the &#8220;hello World&#8221; text on it.</p>

<h2>Two Heads Better Than One</h2>

<p>This is what I love about NSCoder Night. You get some Cocoa geeks together and the collective wisdom starts this synergy where we can bounce things off each other and a solution emerges.</p>

<p>Chad, in the mean time, had been searching the web for some examples and at about the time I started to wonder if there was a Core Animation specific layer for Quartz Compositions, he said, &#8220;QCCompositionLayer&#8221;. Marcus and I were both at that point thinking, &#8220;ah, I should have thought of that since there are Core Animation layers to do everything else media related.&#8221;</p>

<p>I then went to town slinging some code and here is what I came up with:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #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><span style="color: #002200;">&#91;</span>window contentView<span style="color: #002200;">&#93;</span> setWantsLayer<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  QCCompositionLayer <span style="color: #002200;">*</span>layer <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>QCCompositionLayer alloc<span style="color: #002200;">&#93;</span> 
            initWithFile<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;/Developer/Examples/Quartz Composer/Plugins/OpticalFlow/Teapotii.qtz&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>layer setFrame<span style="color: #002200;">:</span>NSRectToCGRect<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>window contentView<span style="color: #002200;">&#93;</span> frame<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  CATextLayer <span style="color: #002200;">*</span>text <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CATextLayer layer<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>text setString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;hello World&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>text setFrame<span style="color: #002200;">:</span>NSRectToCGRect<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>window contentView<span style="color: #002200;">&#93;</span> frame<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>ayer addSublayer<span style="color: #002200;">:</span>text<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>window contentView<span style="color: #002200;">&#93;</span> layer<span style="color: #002200;">&#93;</span> addSublayer<span style="color: #002200;">:</span>layer<span style="color: #002200;">&#93;</span>;    
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>I got rid of the QCView altogether and just added the Quartz Composer layer to the sublayers of the window&#8217;s content view. The Quartz Composition in a QCCompositionLayer begins to play automatically, so really this code is all there is to it. And notice that the text overlay works as well. You could really add anything you wanted in a Core Animation layer at this point.</p>

<h2>Your Own Composition</h2>

<p>If you&#8217;re anything like me this will whet your appetite for playing with some very cool technology. I decided to create my own Quartz Composition and include that in the demo project. The demo composition takes the vide input of your iSight camera and applies the image to each side of a cube. It then rotates the cube. Creating the composition was pretty easy with a cursory reading of Apple&#8217;s <a href="http://developer.apple.com/documentation/GraphicsImaging/Conceptual/QuartzComposerUserGuide/qc_intro/chapter_1_section_1.html">Quartz Composer User Guide</a>. It&#8217;s quite helpful.</p>

<p>You can take a look at the Quartz Composition in Quartz Composer. The <a href='http://www.cimgf.com/wp-content/uploads/2008/09/caquartzcomposition.zip'>demo application</a> has two .qtz files in it. You can just double click either of those from the Finder to see what I did. The one I&#8217;m using in the demo app is the one called &#8220;VideoCub.qtz&#8221;. You can switch it in the code to see the other one as well, which is a quad of four iSight inputs.</p>

<div id="attachment_294" class="wp-caption alignleft" style="width: 160px"><a href="http://www.cimgf.com/wp-content/uploads/2008/09/vidcubeeditor.jpg" rel='lightbox'><img src="http://www.cimgf.com/wp-content/uploads/2008/09/vidcubeeditor-150x150.jpg" alt="VideoCube QC Editor" title="VideoCube QC Editor" width="150" height="150" class="size-thumbnail wp-image-294" /></a><p class="wp-caption-text">VideoCube QC Editor</p></div>

<div id="attachment_297" class="wp-caption alignleft" style="width: 310px"><a href="http://www.cimgf.com/wp-content/uploads/2008/09/qclayer.jpg" rel='lightbox'><img src="http://www.cimgf.com/wp-content/uploads/2008/09/qclayer-300x237.jpg" alt="Quartz Composer Layer" title="Quartz Composer Layer" width="300" height="237" class="size-medium wp-image-297" /></a><p class="wp-caption-text">Quartz Composer Layer</p></div>

<p>You can see I added a CATextLayer to the QCCompositionLayer which displays the words, &#8220;hello World&#8221;. I also applied a Gaussian blur filter to the whole thing so you can see how easy it is to add filters as well. Here is <em>all</em> of the code needed to make this work.</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
</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>awakeFromNib;
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>window contentView<span style="color: #002200;">&#93;</span> setWantsLayer<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>path <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSBundle</span> mainBundle<span style="color: #002200;">&#93;</span> 
                      pathForResource<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;VideoCube&quot;</span> 
                      ofType<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;qtz&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    QCCompositionLayer <span style="color: #002200;">*</span>layer <span style="color: #002200;">=</span> 
        <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>QCCompositionLayer alloc<span style="color: #002200;">&#93;</span> initWithFile<span style="color: #002200;">:</span>path<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span>layer setFrame<span style="color: #002200;">:</span>NSRectToCGRect<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>window contentView<span style="color: #002200;">&#93;</span> frame<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    CATextLayer <span style="color: #002200;">*</span>text <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CATextLayer layer<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>text setString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;hello World&quot;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>text setFrame<span style="color: #002200;">:</span>NSRectToCGRect<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>window contentView<span style="color: #002200;">&#93;</span> frame<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>layer addSublayer<span style="color: #002200;">:</span>text<span style="color: #002200;">&#93;</span>;
&nbsp;
    CIFilter <span style="color: #002200;">*</span>blurFilter <span style="color: #002200;">=</span> 
    <span style="color: #002200;">&#91;</span>CIFilter filterWithName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;CIGaussianBlur&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span>blurFilter setDefaults<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>blurFilter setValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithFloat<span style="color: #002200;">:</span><span style="color: #2400d9;">2.0</span><span style="color: #002200;">&#93;</span> 
                  forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;inputRadius&quot;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>blurFilter setName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;blur&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span>layer setFilters<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithObject<span style="color: #002200;">:</span>blurFilter<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
&nbsp;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>window contentView<span style="color: #002200;">&#93;</span> layer<span style="color: #002200;">&#93;</span> addSublayer<span style="color: #002200;">:</span>layer<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>What&#8217;s even more exciting to me is that if you know a bit of OpenGL, you can do all kinds of other manipulations of the image since QCCompositionLayer inherits from CAOpenGLLayer. Take a close look at -drawInCGLContext in the CAOpenGLLayer API docs. There is a ton of great potential there.</p>

<h2>Conclusion</h2>

<p>The conclusion is that Quartz Compositions are very cool and they are now even cooler since you can work with them in Core Animation. Take a look a the Quartz Composer guide and start building your own compositions that you can easily incorporate into your Core Animation based applications. Until next time.</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2008/09/caquartzcomposition.zip'><img src="http://www.cimgf.com/wp-content/uploads/2008/03/xcode.png" alt="xcode.png" border="0" width="64"/><br />Quartz Composition Layer Demo Project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/09/24/core-animation-tutorial-core-animation-and-quartz-composer-qccompositionlayer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cocoa Tutorial: Adding Plugins to a Cocoa Application</title>
		<link>http://www.cimgf.com/2008/09/17/cocoa-tutorial-adding-plugins-to-a-cocoa-application/</link>
		<comments>http://www.cimgf.com/2008/09/17/cocoa-tutorial-adding-plugins-to-a-cocoa-application/#comments</comments>
		<pubDate>Wed, 17 Sep 2008 17:45:11 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=272</guid>
		<description><![CDATA[A couple of weeks ago we discussed how to build frameworks and how to bundle them with a Cocoa application. This week we are going to build on that knowledge and add Plug-ins to a Cocoa application. Why are these topics linked? Generally, there are a few ways to add plug-ins to a Cocoa application. [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of weeks ago we discussed <a href="http://www.cimgf.com/2008/09/04/cocoa-tutorial-creating-your-very-own-framework/">how to build frameworks and how to bundle them with a Cocoa application</a>.  This week we are going to build on that knowledge and add Plug-ins to a Cocoa application.</p>

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

<h2>Why are these topics linked?</h2>

<p>Generally, there are a few ways to add plug-ins to a Cocoa application.</p>

<h3>Scriptable plug-ins</h3>

<p>Scriptable plug-ins are probably the easiest to add to an application.  They exist in a known location where the application can load them and run them in the appropriate virtual machine.  This makes them fairly easy to construct even though the code to run them may be rather complicated.</p>

<h3>Publishing a Formal Protocol Plug-ins Interface</h3>

<p>This one is a bit more complicated.  The developer (you and me) publish a formal protocol that the plug-ins must adhere to.  This design works rather well but does not allow us, the application developer, to impart any functionality to the plug-ins easily.</p>

<h3>Publishing an Informal Protocol Plug-ins Interface</h3>

<p>This is very similar to the formal plug-ins above but a little more tricky.  Since the protocol is informal, we have to test for each method that we want to use in the plug-ins before we can use it.  Again, it does not make it very easy for us to impart functionality to the plug-ins.</p>

<h3>Publishing a Base Class Plug-ins Interface</h3>

<p>This is the hardest option I have found so far.  Not only do we have to give our plug-ins developers a header file but something to actually compile against.  However, with a base class we can easily impart functionality to our plug-ins without the plug-ins developer having to jump through <em>too many</em> hoops.</p>

<p>Creating a base class solution is where frameworks come in.  It makes it fairly trivial to hand off a base class to plug-ins developers when we give them a framework.  Therefore, we are going to add one class to the plug-ins we wrote previously with the following header:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &lt;Cocoa/Cocoa.h&gt;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> AbstractPlugin <span style="color: #002200;">:</span> <span style="color: #400080;">NSObject</span> 
<span style="color: #002200;">&#123;</span>
&nbsp;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>name;
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>fire<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender;
&nbsp;
<span style="color: #a61390;">@end</span></pre></div></div>


<p>And since I like to make it stupidly easy for people, we are going to use the following implementation of the base &#8220;abstract&#8221; class:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;AbstractPlugin.h&quot;</span>
&nbsp;
<span style="color: #6e371a;">#define kErrFormat @&quot;%s not implemented in subclass %@&quot;</span>
<span style="color: #6e371a;">#define kExceptName @&quot;CIMGF&quot;</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> AbstractPlugin
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>name;
<span style="color: #002200;">&#123;</span>
  <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>reason <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span>kErrFormat, 
    _cmd, <span style="color: #002200;">&#91;</span>self class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">@throw</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSException</span> exceptionWithName<span style="color: #002200;">:</span>kExceptName 
                                 reason<span style="color: #002200;">:</span>reason 
                               userInfo<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>IBAction<span style="color: #002200;">&#41;</span>fire<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;">NSString</span> <span style="color: #002200;">*</span> reason <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span>kErrFormat, 
    _cmd, <span style="color: #002200;">&#91;</span>self class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">@throw</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSException</span> exceptionWithName<span style="color: #002200;">:</span>kExceptName 
                                 reason<span style="color: #002200;">:</span>reason 
                               userInfo<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: #a61390;">@end</span></pre></div></div>


<p>For every method that the subclass <strong>must</strong> override the abstract class will throw an exception if it is not overwritten with a polite message explaining what method in which class is missing.</p>

<h2>Building the plug-ins</h2>

<p>A plug-ins is effectively just a bundle, like a framework or an application.  Inside of the bundle is a Contents directory, MacOS directory (where the binary goes) and a Resources directory.</p>

<div style="text-align:center;">

<a href="http://www.cimgf.com/wp-content/uploads/2008/09/bundlestructure.png" rel="lightbox" title="Bundle Structure">

<img src="http://www.cimgf.com/wp-content/uploads/2008/09/bundlestructure.png" width="50%" alt="Bundle Structure"/>

</a>
</div>

<p>Xcode has a template for building plug-ins that we can use to get started.  For this first plug-ins, we are going to just add it to our existing project as a new target.</p>

<div style="text-align:center;">

<a href="http://www.cimgf.com/wp-content/uploads/2008/09/newproject.png" rel="lightbox" title="New Bundle Project">

<img src="http://www.cimgf.com/wp-content/uploads/2008/09/newproject.png" width="50%" alt="New Bundle Project"/>

</a>
</div>

<p>This new target is very similar to the Framework target that we built previously.  We want to drag it up into the Application&#8217;s target so that it is a dependency; this can also be done from the Get Info window.  We will also want to add the Framework product as a linked framework in the plug-ins.  The end result looks like this.</p>

<div style="text-align:center;">

<a href="http://www.cimgf.com/wp-content/uploads/2008/09/targetstructure.png" rel="lightbox" title="Target Structure">

<img src="http://www.cimgf.com/wp-content/uploads/2008/09/targetstructure.png" width="50%" alt="Target Structure"/>

</a>
</div>

<p>Once we have the target set up, it is time to add some code.  Plug-ins needs to have either a main class defined or a main nib defined.  It is this definition that helps determine how to launch the bundle.  In our case, we will want to define a main class which will be explained below.  To define a main class (or nib), we need to look at the properties tab of the target.</p>

<div style="text-align:center;">

<a href="http://www.cimgf.com/wp-content/uploads/2008/09/propertiestab.png" rel="lightbox" title="Properties Tab">

<img src="http://www.cimgf.com/wp-content/uploads/2008/09/propertiestab.png" width="50%" alt="Properties Tab"/>

</a>
</div>

<p>The next step is to create the main class for our plug-ins.  Since we are using a base class design for our plug-ins, our main class must extend the AbstractPlugin class and it needs to import the framework directly in the header.  For our example, our plug-ins is going to display a new window on the screen, therefore the header must also include a NSWindow attribute and since we want to programmatically close the window, a -closeWindow: IBAction.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &lt;Cocoa/Cocoa.h&gt;</span>
<span style="color: #6e371a;">#import &lt;Example/Example.h&gt;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> PluginMainClass <span style="color: #002200;">:</span> AbstractPlugin 
<span style="color: #002200;">&#123;</span>
  IBOutlet <span style="color: #400080;">NSWindow</span> <span style="color: #002200;">*</span>mainWindow;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>closeWindow<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender;
&nbsp;
<span style="color: #a61390;">@end</span></pre></div></div>


<p>Note that we are importing the framework which contains the AbstractPlugin super class we built earlier.</p>

<p>Once we have the main class defined it is time to build the user interface to go along with this plug-ins.  It is not a requirement that plug-ins have a user interface, they can be pure code instead.  However for the sake of completeness, we are going to add one for this example.</p>

<div style="text-align:center;">

<a href="http://www.cimgf.com/wp-content/uploads/2008/09/pluginwindowstructure.png" rel="lightbox" title="Plug-ins Window Structure">

<img src="http://www.cimgf.com/wp-content/uploads/2008/09/pluginwindowstructure.png" width="50%" alt="Plug-ins Window Structure"/>

</a>
</div>

<p>The structure of the plug-ins nib is simple.  The file owner is the PluginMainClass we wrote previously and there is one window which we bind to the file owner.</p>

<div style="text-align:center;">

<a href="http://www.cimgf.com/wp-content/uploads/2008/09/pluginwindow.png" rel="lightbox" title="Plug-ins Window">

<img src="http://www.cimgf.com/wp-content/uploads/2008/09/pluginwindow.png" width="50%" alt="Plug-ins Window"/>

</a>
</div>

<p>The window is also equally simple, just one button that binds back to the file owner&#8217;s -closeWindow: method.</p>

<p>The last step is to add a copy phase to our application.  Like the framework copy phase we built last time, this is a &#8220;Copy Files&#8221; build phase and we need to configure it to copy files to the &#8220;PlugIns&#8221; directory.  This is another top level directory next to Resources and Frameworks.  Once the build phase is added, drag the plug-ins product into that build phase.</p>

<p>With the window and the main class built we can compile the plug-ins and make sure everything is ready for inclusion into our application.  Once the app is built, we should see a copy of the plug-ins inside of the application bundle.  Now it is time to dynamically load the bundle.</p>

<p>The flow of loading bundles dynamically is as follows:</p>

<ol>
  <li>Find the paths of the bundles.</li>
  <li>Instantiate NSBundle objects for the paths.</li>
  <li>Execute the -load method on the bundle.</li>
  <li>Retrieve the principal class from the bundle.</li>
  <li>Instantiate an object from the principal class.</li>
</ol>

<p>And the code for this is as follows:</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>loadPlugins
<span style="color: #002200;">&#123;</span>
  <span style="color: #400080;">NSBundle</span> <span style="color: #002200;">*</span>main <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSBundle</span> mainBundle<span style="color: #002200;">&#93;</span>;
  <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>all <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>main pathsForResourcesOfType<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;bundle&quot;</span> 
                                   inDirectory<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;../PlugIns&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #400080;">NSMutableArray</span> <span style="color: #002200;">*</span>availablePlugins <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableArray</span> array<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #a61390;">id</span> plugin <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
  <span style="color: #400080;">NSBundle</span> <span style="color: #002200;">*</span>pluginBundle <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
  <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>path <span style="color: #a61390;">in</span> all<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    pluginBundle <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSBundle</span> bundleWithPath<span style="color: #002200;">:</span>path<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>pluginBundle load<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">Class</span> prinClass <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>pluginBundle principalClass<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>prinClass isSubclassOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>AbstractPlugin 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;">continue</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    plugin <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>prinClass alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>availablePlugins addObject<span style="color: #002200;">:</span>plugin<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>plugin release<span style="color: #002200;">&#93;</span>, plugin <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
    pluginBundle <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #a61390;">return</span> availablePlugins;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>In this new method that we have added to the AppDelegate we first get a reference to the main bundle and we then request a path for every file in the PlugIns directory that has an extension of bundle.  With that array in hand we then start to loop over the array and construct a new NSBundle for each path.  Once the bundle is constructed we ask for it to load.  After the load, we grab its principal class, check to make sure we can use it, and construct an object from it.</p>

<p>Since we want to have a list of the loaded plug-ins, we throw this new object into an array that will be returned back from the method.  Once this method is complete we now have every plug-ins dynamically loaded and ready to use.  So lets use them!</p>

<p>We really want to call this method before the application has finished loading, therefore we need to add an -init method to our AppDelegate and load the plug-ins there.  This will guarantee that they are loaded before the UI with some obvious benefits.</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;">id</span><span style="color: #002200;">&#41;</span>init
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>super init<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #a61390;">return</span> <span style="color: #a61390;">nil</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>self setPlugins<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self loadPlugins<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>Here are we calling our new -loadPlugins method and setting the returned array into a ivar.  This ivar will then be used by our UI once it loads to display a list of the plug-ins.</p>

<div style="text-align:center;">

<a href="http://www.cimgf.com/wp-content/uploads/2008/09/mainappwindow.png" rel="lightbox" title="Main Application Window">

<img src="http://www.cimgf.com/wp-content/uploads/2008/09/mainappwindow.png" width="50%" alt="Main Application Window"/>

</a>
</div>

<p>The main window has a pop up button with a list of the plug-ins using their inherited -name method for display.  When the run button is clicked, our application will find out which plug-ins were selected via the NSArrayController and call the inherited -run: method on the plug-ins with predictable results.</p>

<h2>Conclusion</h2>

<p>For clarity we did leave a few things out of this project.  For example, there is no code for unloading the plug-ins nor do we search the Application Support directory for user added plug-ins.  However these are easy to add based on the code that was included.</p>

<p>I should also note that we used the default extension for these plug-ins.  I would recommend changing this extension to something unique to your application and add that extension (or UTI) to your main application as an accepted file type.  See previous articles here on CIMGF to see how to do each of those.</p>

<p><center><a href="http://www.cimgf.com/wp-content/uploads/2008/09/frameworks.zip" title="Example Project"><img src="http://www.cimgf.com/wp-content/uploads/2008/03/xcode.png" alt="xcode.png" border="0" width="64"/><br/>Example Project</a></center></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/09/17/cocoa-tutorial-adding-plugins-to-a-cocoa-application/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

