<?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; Objective-C</title>
	<atom:link href="http://www.cimgf.com/category/objective-c/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>Core Data and Threads, Without the Headache</title>
		<link>http://www.cimgf.com/2011/05/04/core-data-and-threads-without-the-headache/</link>
		<comments>http://www.cimgf.com/2011/05/04/core-data-and-threads-without-the-headache/#comments</comments>
		<pubDate>Wed, 04 May 2011 20:12:56 +0000</pubDate>
		<dc:creator>Saul Mora</dc:creator>
				<category><![CDATA[Core Data]]></category>
		<category><![CDATA[GCD & Blocks]]></category>
		<category><![CDATA[NSOperation]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[core-data]]></category>
		<category><![CDATA[gcd]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1388</guid>
		<description><![CDATA[I know I mentioned we would talk about customizing the fetch requests, however, I have been working on some code related to the Active Record Fetching project, which I am renaming to MagicalRecord, that is also just as useful as fetching&#8211;threading. Whenever most cocoa developers mention threading and Core Data in the same sentence, the [...]]]></description>
			<content:encoded><![CDATA[<p>I know I mentioned we would talk about customizing the fetch requests, however, I have been working on some code related to the Active Record Fetching project, which I am renaming to MagicalRecord, that is also just as useful as fetching&#8211;threading.</p>

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

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

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

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

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

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

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


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


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

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

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

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

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

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

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

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

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

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

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


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


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


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


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


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


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

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

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

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

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


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


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

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

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

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


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


<h2>Going the Distance</h2>

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


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


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


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


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


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


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

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

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


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


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


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


<p>Using blocks, GCD and a little bit of convention, we&#8217;ve helped to make multithreaded Core Data code much easier to write and stay consistent with Apple&#8217;s recommended methods. Not only that, but this solution consolodates much of the manual boilerplate setup required to properly save data in the background and safely update data throughout your applications.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/05/04/core-data-and-threads-without-the-headache/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Super Happy Easy Fetching in Core Data</title>
		<link>http://www.cimgf.com/2011/03/13/super-happy-easy-fetching-in-core-data/</link>
		<comments>http://www.cimgf.com/2011/03/13/super-happy-easy-fetching-in-core-data/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 05:30:04 +0000</pubDate>
		<dc:creator>Saul Mora</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[core-data]]></category>

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

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

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

<h2>Easy Fetches</h2>

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


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


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

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

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

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

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

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

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


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


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


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


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


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


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

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


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


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

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


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


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


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


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

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


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


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

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

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

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

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

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

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

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


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


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


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


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

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

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

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

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


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


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

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

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

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

<h2>Implementing Draw Rect</h2>

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


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


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

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


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


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


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


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

<h2>Conclusion</h2>

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

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

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

<p>When running on the device the image I am tiling is just too large to be tiled completely before the app uses up too much memory and is killed. You will probably want to run in the simulator to see the tiling finish. As noted in the code comments, you un-comment the tiling code and do a first run with the app allowing it to finish tiling. Then, stop the app and re-comment that tiling code and it will just load and display the tiles it created without having to go through that tiling again. I suppose I could have made the tiling code get called in response to a button tap or something like that, but I&#8217;ll leave that as an exercise for the reader. Contact me through the comments below if you have any problems or questions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/03/01/subduing-catiledlayer/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Passing around a NSManagedObjectContext on iOS</title>
		<link>http://www.cimgf.com/2011/01/07/passing-around-a-nsmanagedobjectcontext-on-the-iphone/</link>
		<comments>http://www.cimgf.com/2011/01/07/passing-around-a-nsmanagedobjectcontext-on-the-iphone/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 19:23:46 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1274</guid>
		<description><![CDATA[This article is reprinted from the MDN The documentation on Core Data for the iPhone has lead to some confusion about how best to use Core Data on a Cocoa Touch device. One particular section seems to be the most confusing, specifically: A view controller typically shouldn’t retrieve the context from a global object such [...]]]></description>
			<content:encoded><![CDATA[<p><strong>This article is reprinted from the MDN</strong></p>

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

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

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

<h2>Why Rigidity is bad</h2>

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

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

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

<h2>Solution One</h2>

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

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

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

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

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

<h2>Solution two</h2>

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

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

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

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

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

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

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

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

@property (nonatomic, retain) NSManagedObjectContext *moc;

@end
</code></pre>

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

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

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

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

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

<h2>Solution three</h2>

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

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

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

<h2>Conclusion</h2>

<p>The overall idea behind this article is to keep each view controller separate from anything up stream or in a different silo.  This will make the design far more flexible in the long run.  Any time that you feel the &#8220;need&#8221; to pass in a parent view controller to a child view controller, reconsider the design.  Consider using a <code>@protocol</code> delegate design or NSNotification calls instead.  Keep each view controller as its own private island.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2011/01/07/passing-around-a-nsmanagedobjectcontext-on-the-iphone/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Differentiating Tap Counts on iOS [UPDATED]</title>
		<link>http://www.cimgf.com/2010/06/14/differentiating-tap-counts-on-ios/</link>
		<comments>http://www.cimgf.com/2010/06/14/differentiating-tap-counts-on-ios/#comments</comments>
		<pubDate>Mon, 14 Jun 2010 23:02:08 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa Touch]]></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=1072</guid>
		<description><![CDATA[In your iPhone/iPad apps you often need to know how many times your user tapped in a view. This can be challenging because, though the user may have tapped twice, you will receive the event and it will look like they tapped once as well as twice. If the user triple-tapped, you will get the [...]]]></description>
			<content:encoded><![CDATA[<p>In your iPhone/iPad apps you often need to know how many times your user tapped in a view. This can be challenging because, though the user may have tapped twice, you will receive the event and it will look like they tapped once as well as twice. If the user triple-tapped, you will get the event for one tap, two taps, and three taps. It can get a little frustrating, but the trick is timing. You simply have to wait a period of time to see if another tap comes. If it does, you cancel the action spawned by the first tap. If it doesn&#8217;t you allow the action to run. There&#8217;s a few little nuances to getting it to work, but it can be done. Here is how.
<span id="more-1072"></span></p>

<h2>Overriding Touch Event Handlers</h2>

<p>In order to know how many times your user tapped, you listen for the events in the various touch handlers. Let start with -touchesEnded. This is where we will determine how many taps we received and respond accordingly. Consider 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
</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>touchesEnded<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSSet</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>touches withEvent<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIEvent<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>event 
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span>touches.count <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: #a61390;">if</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>touches anyObject<span style="color: #002200;">&#93;</span> tapCount<span style="color: #002200;">&#93;</span> <span style="color: #002200;">==</span> <span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
      <span style="color: #002200;">&#91;</span>self handleDoubleTap<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><span style="color: #002200;">&#91;</span>touches anyObject<span style="color: #002200;">&#93;</span> tapCount<span style="color: #002200;">&#93;</span> <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: #002200;">&#91;</span>self handleTripleTap<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: #002200;">&#91;</span>self handleSingleTap<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>If you place a breakpoint inside each of the code blocks for the three tap counts, you will find that in the case where you triple tap, it will break in all three. If you double tap, it will break in both the double tap and single tap and of course if you single tap, it will break in the single tap branch.</p>

<p>In most cases, this is not desirable. You will likely want a clean differentiation between each touch as each tap count will likely mean something different. So how can we fix this? The trick is to use <em>-peformSelector:withObject:afterDelay</em> and then canceling the perform action if a new action occurs. Got it?</p>

<h2>Wait For It&#8230;</h2>

<p>If you call the method directly as we did in the sample code above, there is no way to delay when it runs nor is there a way to cancel it should another tap be received. Both of these things are necessary. If you think about it, waiting to run our <em>-handleSingleTap</em> method until a certain amount of time passes helps make sure it actually was a double tap. If the user taps once and nothing else occurs, we&#8217;re safe to run the <em>-handleSingleTap</em> code. If another tap is received in the mean time, however, we can cancel the action from the first tap. The way we do this is by changing our <em>-touchesEnded:</em> code to something 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
</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>touchesEnded<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSSet</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>touches withEvent<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIEvent<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>event 
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span>touches.count <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: #a61390;">if</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>touches anyObject<span style="color: #002200;">&#93;</span> tapCount<span style="color: #002200;">&#93;</span> <span style="color: #002200;">==</span> <span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</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>handleDoubleTap<span style="color: #002200;">&#41;</span>
                 withObject<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span>
                 afterDelay<span style="color: #002200;">:</span><span style="color: #2400d9;">0.35</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;">&#91;</span><span style="color: #002200;">&#91;</span>touches anyObject<span style="color: #002200;">&#93;</span> tapCount<span style="color: #002200;">&#93;</span> <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: #002200;">&#91;</span>self handleTripleTap<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: #002200;">&#91;</span>self performSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>handleSingleTap<span style="color: #002200;">&#41;</span>
                 withObject<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span>
                 afterDelay<span style="color: #002200;">:</span><span style="color: #2400d9;">0.35</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>Notice that we are delaying 350 milliseconds to see if another event occurs. You should also notice that we still call <em>-handleTripleTap</em> directly without using <em>-performSelector:withObject:afterDelay</em>. This is because it has now been isolated as a distinct event. If we get a triple tap, we&#8217;re pretty well assured now that a double or single tap event was not actually run as those events will have been cancelled. So how does that work? How do we cancel them?</p>

<h2>Canceling The Action</h2>

<p>Now that we are waiting around to see if another tap event occurs, we need to override the <em>-touchesBegan:</em> method. It will look something like this:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</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>touchesBegan<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSSet</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>touches withEvent<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIEvent<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>event
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSObject</span> cancelPreviousPerformRequestsWithTarget<span style="color: #002200;">:</span>self
                                           selector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>handleSingleTap<span style="color: #002200;">&#41;</span>
                                             object<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSObject</span> cancelPreviousPerformRequestsWithTarget<span style="color: #002200;">:</span>self
                                           selector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>handleDoubleTap<span style="color: #002200;">&#41;</span>
                                             object<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>The method <em>-cancelPreviousPerformRequestsWithTarget:selector:object:</em> is able to determine which action you want to cancel and then cancel it preventing the selectors, <em>-handleSingleTap</em> or <em>-handleDoubleTap</em> from being called&#8211;assuming the second or third taps occurred within the allocated 350 milliseconds. That&#8217;s all there is to it.</p>

<h2>There *Is* a Catch</h2>

<p>That is all there is to it, however, you have to be careful if you intend to pass parameters to your selectors. If you use a selector that takes a parameter so that you have to call something with <em>-performSelector:withObject:afterDelay:</em> passing an object to the second parameter, you will need <em>that</em> object or one identical to it in your call to cancel the action with <em>-cancelPreviousPerformRequestsWithTarget:selector:object:</em>. It must be able to evaluate to true when <em>equals</em> is called on the object passed into the <em>object</em> parameter. This can be tricky, but you can overcome it in one of two ways using an ivar:</p>

<ul>
<li><p>Create an ivar to hold onto the variable that you will use as a parameter to the cancel when you first pass it to the <em>-performSelector:withObject:afterDelay:</em> call.</p></li>
<li><p>Create an ivar to hold onto the variable when you first enter touches ended and call <em>-performSelector:withObject:afterDelay</em> passing it nil for the <em>object</em> parameter. Then, grab the ivar when you need it in your handler code. The cancel call can then take nil for its <em>object</em> parameter.</p></li>
</ul>

<p>These points are crucial if you are intending to pass parameters as the cancel will fail if you try to pass a parameter and it doesn&#8217;t match what you used in your call to <em>-performSelector:withObjecct:afterDelay:</em>. The only parameter that doesn’t matter is the <em>afterDelay:</em> param.</p>

<h2>Conclusion</h2>

<p>I&#8217;m finding the need to differentiate tap counts more and more often so this post is really as much a way for me to keep a journal of things I need to do frequently as it is to help others figure things out too. I hope it&#8217;s been helpful to you. Until next time.</p>

<h1>Update</h1>

<p>So, apparently Gesture Recognizers do address this issue. I had looked at them as a possible solution, but ran into the same differentiation problems, hence this blog post. However, <a href="http://twitter.com/aclark">Ashley Clark</a> pointed me to the <em><a href="http://developer.apple.com/iphone/library/documentation/uikit/reference/UIGestureRecognizer_Class/Reference/Reference.html#//apple_ref/occ/instm/UIGestureRecognizer/requireGestureRecognizerToFail:">-requireGestureRecognizerToFail:</a></em> method, which apparently enables you to have this cancellation functionality by creating a dependency between recognizers. The code to take advantage of it looks something 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
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;">UITapGestureRecognizer <span style="color: #002200;">*</span>tripleTap <span style="color: #002200;">=</span> 
<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UITapGestureRecognizer alloc<span style="color: #002200;">&#93;</span>
 initWithTarget<span style="color: #002200;">:</span>self action<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>handleTripleTap<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>tripleTap setNumberOfTapsRequired<span style="color: #002200;">:</span><span style="color: #2400d9;">3</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self view<span style="color: #002200;">&#93;</span> addGestureRecognizer<span style="color: #002200;">:</span>tripleTap<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>tripleTap release<span style="color: #002200;">&#93;</span>;
&nbsp;
UITapGestureRecognizer <span style="color: #002200;">*</span>doubleTap <span style="color: #002200;">=</span> 
<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UITapGestureRecognizer alloc<span style="color: #002200;">&#93;</span>
 initWithTarget<span style="color: #002200;">:</span>self action<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>handleDoubleTap<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>doubleTap setNumberOfTapsRequired<span style="color: #002200;">:</span><span style="color: #2400d9;">2</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>doubleTap requireGestureRecognizerToFail<span style="color: #002200;">:</span>tripleTap<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self view<span style="color: #002200;">&#93;</span> addGestureRecognizer<span style="color: #002200;">:</span>doubleTap<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>doubleTap release<span style="color: #002200;">&#93;</span>;
&nbsp;
UITapGestureRecognizer <span style="color: #002200;">*</span>singleTap <span style="color: #002200;">=</span> 
<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UITapGestureRecognizer alloc<span style="color: #002200;">&#93;</span>
 initWithTarget<span style="color: #002200;">:</span>self action<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>handleSingleTap<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>singleTap setNumberOfTapsRequired<span style="color: #002200;">:</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span>; <span style="color: #11740a; font-style: italic;">// Unnecessary since it's the default</span>
<span style="color: #002200;">&#91;</span>singleTap requireGestureRecognizerToFail<span style="color: #002200;">:</span>doubleTap<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self view<span style="color: #002200;">&#93;</span> addGestureRecognizer<span style="color: #002200;">:</span>singleTap<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>singleTap release<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>So, if your project is 3.2 and later, use gesture recognizers. The effect is about the same, but the code is quite a bit cleaner.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2010/06/14/differentiating-tap-counts-on-ios/feed/</wfw:commentRss>
		<slash:comments>9</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>Fixing the UISplitViewController Template</title>
		<link>http://www.cimgf.com/2010/05/24/fixing-the-uisplitviewcontroller-template/</link>
		<comments>http://www.cimgf.com/2010/05/24/fixing-the-uisplitviewcontroller-template/#comments</comments>
		<pubDate>Mon, 24 May 2010 16:37:18 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=1019</guid>
		<description><![CDATA[The default implementation of the UISplitViewController based template in Xcode does not provide a navigation controller stack in the detail view. Instead it is just a regular old view with a navigation bar at the top. I suppose there are cases when you might want such an implementation, however, i think you would more commonly [...]]]></description>
			<content:encoded><![CDATA[<p>The default implementation of the UISplitViewController based template in Xcode does not provide a navigation controller stack in the detail view. Instead it is just a regular old view with a navigation bar at the top. I suppose there are cases when you might want such an implementation, however, i think you would more commonly want there to be a navigation stack for cases when you wan to push new view controllers for your users to see. In this post i intend to demonstrate how to convert the default template to something more useable.
<span id="more-1019"></span></p>

<h2>Gut The Default Template</h2>

<p>It&#8217;s not quite as drastic as the work &#8216;gut&#8217; might imply, but you want to remove some things from the default template nib. To get started create a Split View project, by selecting <strong>File | New Project&#8230;</strong> in Xcode. Then choose <strong>Split View-based Application</strong> and click <strong>Choose&#8230;</strong>. Name your application. I called mine <strong>&#8216;SpiffySplitView&#8217;</strong>.</p>

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

<p>Double-click <em>DetailView.xib</em> under the Resources group in your newly created project. This will open Interface Builder.</p>

<p>The first thing you will notice in the Interface Builder editor is that there is a UINavigationBar at the top. Select this bar and delete it. We will be switching the detail view of this split view project to use a UINavigationController which will add this nav bar back in for us but will provide the whole navigation stack along with it providing us the flexibility to push new view controllers in the detail view.</p>

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

<p>In the View inspector you will also want to make the Orientation Landscape, make the Top Bar a Navigation Bar, and set the Split View option to &#8220;Detail&#8221;.</p>

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

<p>Once you have made these changes, save the nib and switch back to Xcode. Now, double click the <em>MainWindow.xib</em> file in the Resources section of your Xcode project which will open it in Interface Builder.</p>

<h2>Implementing a Navigation Controller In The Detail View</h2>

<p>When <em>MainWindow.xib</em> opens in Interface Builder, take a look at the MainWindow.xib resources and switch to the detailed list view if you haven&#8217;t already so that the window looks something like this:</p>

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

<p>Notice that the Split View Controller contains two view controllers. The first one is a navigation controller, but the second one is our detail view controller. The first thing you want to do is change that. From the Library palette in Interface Builder, select the Navigation Controller object and drag and drop it on top of the detail view controller in the resources window.</p>

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

<p>The detail view controller will automatically switch to a navigation controller. Now you need to twirl down the new nav controller and change the root view controller type to a DetailViewController by switching to the Identity tab in the inspector.</p>

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

<p>Finally we are going to need to make our new navigation controller a delegate of the UISplitViewController in order to receive split view change notifications. Drag a connection from the Split View Controller to the Detail View Controller and select <strong>delegate</strong>.</p>

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

<p>Save your work. If you switch back to Xcode and run the application, you may not notice much of a difference in the look of the application, however, we can now make some changes in code that will give us a lot more flexibility.</p>

<h2>Changes In Code</h2>

<p>Edit DetailViewController.m in Xcode and change the -viewDidLoad method to set a title for the view controller. This will get passed up to the navigation controller which will display the title in the navigation bar.</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><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>;
  <span style="color: #002200;">&#91;</span>self setTitle<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Spiffy&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>This code will allow you to see the word &#8216;Spiffy&#8217; in the navigation bar.</p>

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

<p>Next, you will notice that in portrait view, we have no button to tap to see our table view. It is only available in landscape view. To remedy this, you need to change a few lines of code&#8211;again in the DetailViewController you will modify the split view delegate methods. These methods simple add and remove the bar button item depending upon which mode we&#8217;re in, landscape or portrait or more specifically whether we are showing or hiding our list view controller.</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><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>splitViewController<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UISplitViewController<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>svc 
     willHideViewController<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIViewController <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>aViewController 
          withBarButtonItem<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIBarButtonItem<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>barButtonItem 
       forPopoverController<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIPopoverController<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>pc
<span style="color: #002200;">&#123;</span>  
  <span style="color: #002200;">&#91;</span>barButtonItem setTitle<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Root List&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self navigationItem<span style="color: #002200;">&#93;</span> setLeftBarButtonItem<span style="color: #002200;">:</span>barButtonItem<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self setPopoverController<span style="color: #002200;">:</span>pc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>splitViewController<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UISplitViewController<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>svc 
     willShowViewController<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIViewController <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>aViewController 
  invalidatingBarButtonItem<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIBarButtonItem <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>barButtonItem
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self navigationItem<span style="color: #002200;">&#93;</span> setLeftBarButtonItem<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self setPopoverController<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>Now you can see our button show and hide correctly.</p>

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

<p>A problem you my run into now is that when you select one of the items in the list view, the detail view doesn&#8217;t actually update. This is due to the fact that we disconnected things when we changed our detail view controller in the split view to a navigation controller and we never re-connected it. To re-connect, open MainWindow.xib in Interface Builder again by double clicking it from the Resources group in Xcode. Then drag a connection from the root view controller to the Detail View Controller and select <strong>detailViewController</strong>.</p>

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

<h2>The Point</h2>

<p>So now what? The project is, in essence, now back to where it was when we started, right? Except now we can push new view controllers onto the stack. To demonstrate this, let&#8217;s add a button to the detail view controller that will be the trigger for pushing a new view controller and then we can create the new view controller to push.</p>

<p>In Xcode, create an action in the detail view controller that we will connect to. The code will look something 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>IBAction<span style="color: #002200;">&#41;</span>pushNewViewController<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: #11740a; font-style: italic;">// Create and push new view controller here</span>
&nbsp;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>In Xcode, double click the DetailView.xib to open it in Interface Builder. Then add a button to the view. Drag a connection from the new button to the action we just created.</p>

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

<p>Save your changes and go back into Xcode. Select <strong>File | New File&#8230;</strong>. In the ensuing dialog, choose <strong>UIViewController subclass</strong> in the <strong>Cocoa Touch Class</strong> group and make sure you have <strong>Targeted for iPad</strong> and <strong>With XIB for user interface</strong> selected. Click Next and then provide a name. I called my <em>NewViewController</em>.</p>

<p>Double-click the <em>NewViewController.xib</em> file to open it in Interface Builder. Change the settings on the view to do the following:</p>

<ul>
<li>Set orientation to landscape</li>
<li>Set Top Bar to Navigation Bar</li>
<li>Set Split View to Detail</li>
</ul>

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

<p>Save your changes and switch back to Xcode. In the -viewDidLoad of your NewViewController.m file, set the title again.</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><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>;
  <span style="color: #002200;">&#91;</span>self setTitle<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;New View Controller&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Now, in your DetailViewController.m file, #import the NewViewController.h file and then implement the push new view controller action.</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;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>pushNewViewController<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: #11740a; font-style: italic;">// Create and push new view controller here</span>
  NewViewController <span style="color: #002200;">*</span>controller <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NewViewController alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self navigationController<span style="color: #002200;">&#93;</span> pushViewController<span style="color: #002200;">:</span>controller animated<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>controller release<span style="color: #002200;">&#93;</span>, controller <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Now, when you tap the button on the detail view controller, a NewViewController will be pushed onto the navigation stack.</p>

<h2>Conclusion</h2>

<p>There are certainly legitimate reasons to place a navigation bar into your view manually. You might want to just use it as a place for tool bar items or other information. You may not need the navigation controller stack functionality, but providing yourself a way to push a new view controller on the navigation stack opens up additional possibilities while retaining the capabilities you have by using only a navigation bar. As the kids say, &#8220;it&#8217;s all good&#8221;. Until next time.</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2010/05/SpiffySplitView.zip'>SpiffySplitView Xcode Project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2010/05/24/fixing-the-uisplitviewcontroller-template/feed/</wfw:commentRss>
		<slash:comments>21</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>Accessing The Cloud From Cocoa Touch</title>
		<link>http://www.cimgf.com/2010/02/12/accessing-the-cloud-from-cocoa-touch/</link>
		<comments>http://www.cimgf.com/2010/02/12/accessing-the-cloud-from-cocoa-touch/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 19:13:53 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=909</guid>
		<description><![CDATA[Everything is moving toward the cloud and unless you&#8217;re building calculators, unit converters, or miniature golf score keepers your iPhone app needs to know how to get data from it. In this blog post I intend to demonstrate how to set up a simple server application and how to retrieve data from it and post [...]]]></description>
			<content:encoded><![CDATA[<p>Everything is moving toward the cloud and unless you&#8217;re building calculators, unit converters, or miniature golf score keepers your iPhone app needs to know how to get data from it. In this blog post I intend to demonstrate how to set up a simple server application and how to retrieve data from it and post data to it using Cocoa Touch. I have chosen to use PHP on the server side because of it&#8217;s simplicity and ubiquity, and because I&#8217;ve know it, somewhat. You should, however, be able to implement something similar using your server side language of choice.</p>

<p>In many cases when you go to access remote data, you do so through a web service API. While services based on such technologies as SOAP or XML-RPC are standards that provide reasonable methods for retrieving and updating data, REST seems to be the methodology gaining the most ground lately. For our purpose in this post I won&#8217;t get into great detail of how to implement a REST base web service as, again, REST is not a specific implementation but rather a methodology. (Read up on it elsewhere if you don&#8217;t understand what this means). However, I will talk about it briefly so that you can get on the right path for doing your own REST implementation.
<span id="more-909"></span></p>

<h2>What Is The Cloud</h2>

<p>It seems that the term &#8216;cloud&#8217; in this context has been around for a pretty long time, however, you can just think of it as, well, the Internet. If you access your data &#8220;in the cloud&#8221;, you are accessing your data that is hosted on some server somewhere in the world. The idea behind it being that you can always access it no matter where you are. If your data is not &#8220;in the cloud&#8221;, then it is hosted locally only and only accessible from that location.</p>

<p>Amazon.com among other technology leaders has helped to make this metaphor easier to understand. If you are familiar with Amazon S3 (Simple Storage Service), then you know what it means to store your data &#8220;in the cloud&#8221;. Amazon has made it very cheap and very easy to access data that you store on their servers from anywhere in the world. They provide a RESTful web service through which you can securely add, remove, and update data that you have stored there. If you have image or video assets, for example, that you find get accessed a lot through your website, you may find that hosting those files on S3 is cheaper than paying your own web host to provide the bandwidth and storage for them. This is a perfect example of what cloud computing is and provides.</p>

<p>On a more generic level, cloud computing can mean setting up your own service and providing access to resources or data in the same fashion. The difference in this case, however, is that you are managing it all on your own. Let&#8217;s take a look at how you might do this.</p>

<h2>Sending Arbitrary Data</h2>

<p>The simplest PHP script can really teach you a great deal about what is going on between client and server. Remember that since we are depending on the Apache web server to serve up our PHP responses a huge portion of the work is already done. We don&#8217;t have to worry about low-level networking APIs and sockets. Instead we can create a simple connection using a URL and the NSURLConnection class and we&#8217;re most of the way there. Consider the following PHP code sample.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #b1b100;">print</span> <span style="color: #000088;">$HTTP_RAW_POST_DATA</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>


<p>With one line of code (not including the tags), we have just implemented an echo server. Whatever you send to this script on the server will be sent right back to you. You should understand though that it is the <strong>body</strong> of the request that gets stored in this $HTTP_RAW_POST_DATA variable. So what does that mean?</p>

<p>This really means that you can send anything you want as the body of the request and this script will store it in the $HTTP_RAW_POST_DATA and then <em>print</em> it back as the response. You just specify in your request the type of data you&#8217;re sending. Say you want to send raw XML, for example, you specify&#8221;&#8216;text/xml&#8221; as the content-type of the request that you will hand off to your NSURLConnection as in the following code snippet.</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: #400080;">NSMutableURLRequest</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;">NSMutableURLRequest</span> alloc<span style="color: #002200;">&#93;</span> 
        initWithURL<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURL</span> 
        URLWithString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;http://www.cimgf.com/testpost.php&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>request setHTTPMethod<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;POST&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;text/xml&quot;</span> 
              forHTTPHeaderField<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Content-type&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>xmlString <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;&lt;data&gt;&lt;item&gt;Item 1&lt;/item&gt;&lt;item&gt;Item 2&lt;/item&gt;&lt;/data&gt;&quot;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>request setValue<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&quot;</span>,
        <span style="color: #002200;">&#91;</span>xmlString length<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span> 
        forHTTPHeaderField<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Content-length&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>request setHTTPBody<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>xmlString 
        dataUsingEncoding<span style="color: #002200;">:</span>NSUTF8StringEncoding<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: #400080;">NSURLConnection</span> alloc<span style="color: #002200;">&#93;</span> 
        initWithRequest<span style="color: #002200;">:</span>request 
                   delegate<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>When this request finishes, the same XML in the <em>xmlString</em> variable will be sent right back to our application and will be available in our delegate method, <em>- (void)connectionDidFinishLoading:(NSURLConnection *)connection;</em> assuming we&#8217;ve been <a href="http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-161937-CJBHEGJE">appending the data to an NSMutableData object</a> in our delegate method, <em>- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d;</em>.</p>

<p>This example is just echoing back whatever we send, but if we wanted to get a little fancier, we could load and parse the XML with the PHP XML parser and respond back to the client with something more useful.</p>

<p>What is also interesting about this code is that you can replace the body of the request with any data type you&#8217;re interested in POSTing to your server. If you post image data, for example, you can save that image data on the server side using something like this PHP script:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000088;">$handle</span> <span style="color: #339933;">=</span> <span style="color: #990000;">fopen</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;image.png&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;wb&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// write binary</span>
&nbsp;
<span style="color: #990000;">fwrite</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$handle</span><span style="color: #339933;">,</span> <span style="color: #000088;">$HTTP_RAW_POST_DATA</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">fclose</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$handle</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Received image file.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>


<p>Keep in mind that this is very primitive and it does no sanity checking on the body data. You would need to add that in order to implement any real world server side application. That being said, these few lines of code demonstrate how you can send most any data as the request body and process it on the server side. Our Objective-C code from earlier modified to support sending a PNG image would 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
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><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 imageNamed<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;localimage.png&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #400080;">NSMutableURLRequest</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;">NSMutableURLRequest</span> alloc<span style="color: #002200;">&#93;</span> 
        initWithURL<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURL</span> 
        URLWithString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;http://www.cimgf.com/testpostimage.php&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>; <span style="color: #11740a; font-style: italic;">// Not a real URL. </span>
&nbsp;
<span style="color: #002200;">&#91;</span>request setHTTPMethod<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;POST&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image/png&quot;</span> 
        forHTTPHeaderField<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Content-type&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request setValue<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&quot;</span>, 
        <span style="color: #002200;">&#91;</span>imageData length<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span> 
        forHTTPHeaderField<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Content-length&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request setHTTPBody<span style="color: #002200;">:</span>imageData<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURLConnection</span> alloc<span style="color: #002200;">&#93;</span> initWithRequest<span style="color: #002200;">:</span>request delegate<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>The request we are sending will be asynchronous so our UI will not hang, however, there is no accurate progress monitoring capability, so you would need to implement that if you want to have an idea of how long it is going to take to post the image up to the web service. See the section called <strong>Simplifying Cloud Access</strong> below to see one solution to providing progress.</p>

<h2>Working With Web Forms</h2>

<p>A lot of web applications began life as web forms in which the user can obtain a list of records or a detail record based on input the user provides. You can post form data programmatically using a fairly trivial implementation not much different from the code we demonstrated above. In the previous section we discussed that you can send any arbitrary data to a web service or script by placing that data in the body of the request. This is also true for sending form data.</p>

<p>If you send form data, which is the default when you create an NSURLConnection object and use it to talk to your server, you will see a string of key value pairs in the same format you would normally see in a get request&#8211;something like <em>key1=value1&amp;key2=value2&amp;key3=value3</em>, etc. This is what gets sent in the body for web form requests.</p>

<p>Consider the following Bug Reporter web form.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2010/02/fancybugreporter.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2010/02/fancybugreporter-300x94.png" alt="" title="Fancy Bug Reporter Form" width="300" height="94" class="alignleft size-medium wp-image-933" /></a></p>

<p>Yes, yes, I know&#8211;it&#8217;s beautiful. Looks like something you would see circa 1995. Stick with me here as I&#8217;m trying to keep things simple. The form takes two fields and just formats the input and responds to the user with what the user entered. This same form can also be submitted using code similar to what we&#8217;ve already shown. Here is how you would programmatically post data to this form using and NSURLConnection/NSURLRequest.</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: #400080;">NSMutableURLRequest</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;">NSMutableURLRequest</span> alloc<span style="color: #002200;">&#93;</span> initWithURL<span style="color: #002200;">:</span>
            <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURL</span> URLWithString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;http://www.cimgf.com/test/testform.php&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>request setHTTPMethod<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;POST&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>postString <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;go=1&amp;name=Bad%20Bad%20Bug&amp;description=This%20bug%20is%20really%20really%20super%20bad.&quot;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>request setValue<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&quot;</span>, <span style="color: #002200;">&#91;</span>postString length<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span> 
        forHTTPHeaderField<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Content-length&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>request setHTTPBody<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>postString 
        dataUsingEncoding<span style="color: #002200;">:</span>NSUTF8StringEncoding<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: #400080;">NSURLConnection</span> alloc<span style="color: #002200;">&#93;</span> 
        initWithRequest<span style="color: #002200;">:</span>request delegate<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>Notice that we are passing a variable called <em>go</em> in the postString variable. This tells our PHP script to see the request as if the submit button was clicked. You&#8217;ll notice in the PHP script that we are checking whether the submit button was clicked with the call to isset($_POST['go']). Take a look at the complete PHP web form script.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">&lt;html&gt;
&lt;head&gt;&lt;title&gt;Bug Reporter&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;
&lt;h2&gt;Fancy Bug Reporter&lt;/h2&gt;
&lt;hr /&gt;
<span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'go'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// Form was posted</span>
        <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;User submitted bug: &quot;</span><span style="color: #339933;">.</span> <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'name'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;: &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'description'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #b1b100;">else</span>
<span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// Form was not posted, display form</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span>
&lt;form method=&quot;POST&quot; action=&quot;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$PHP_SELF</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&quot;&gt;
Bug Name:&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;name&quot; maxlength=&quot;100&quot; /&gt;&lt;br /&gt;
Bug Description:&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;description&quot; maxlength=&quot;1000&quot; size=&quot;80&quot; /&gt;&lt;br /&gt;
&lt;input type=&quot;submit&quot; name=&quot;go&quot; value=&quot;Add Bug&quot;&gt;
&lt;/form&gt;
<span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span>
&lt;/body&gt;
&lt;/html&gt;</pre></td></tr></table></div>


<p>When the request finishes posting to this form, you will have the same HTML code in your data object as what you would see if you were to view the source in the actual web page after posting the form.</p>

<h2>Simplifying Cloud Access</h2>

<p><a href="http://twitter.com/pokeb">Ben Copsey</a> developed a networking library called <a href="http://allseeing-i.com/ASIHTTPRequest/">ASIHTTPRequest</a> that is a really good replacement for NSURLConnection and related classes. There are a couple reasons I prefer it to NSURLConnection. These include:</p>

<ul>
<li>You can specify a delegate selector when you create your request object that will get called back when the request fails or succeeds. This is really just a preference over NSURLConnection/NSURLRequest as it just seems simpler to me.</li>
<li>If you do want to see accurate progress for either downloads or uploads, you can pass in a reference to a UIActivityIndicatorView that will be updated automatically</li>
<li>Different types of classes are available for different types of requests. For example, to post form data to a web form, you use ASIFormDataRequest instead of the more generic ASIHTTPRequest. It handles setting up the request body correctly and even enables you to post a file to the form if the form accepts one.</li>
<li>While Ben still considers it <em>experimental</em> code, there is also support for access to Amazon&#8217;s S3. You create an <a href="http://allseeing-i.com/ASIHTTPRequest/S3">ASIS3Request</a> object and provide your S3 credentials to the request. Then you can create, update, or delete any assets you may be storing in your S3 buckets.</li>
</ul>

<p>Using the example I mentioned earlier of sending XML to our PHP echo script, the request would now look like the following using the ASIHTTPRequest object:</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;">ASIHTTPRequest <span style="color: #002200;">*</span>request <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>ASIHTTPRequest requestWithURL<span style="color: #002200;">:</span>url<span style="color: #002200;">&#93;</span>;
<span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>xmlString <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;&lt;data&gt;&lt;item&gt;Item 1&lt;/item&gt;&lt;item&gt;Item 2&lt;/item&gt;&lt;/data&gt;&quot;</span>;
<span style="color: #002200;">&#91;</span>request appendPostData<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>xmlString dataUsingEncoding<span style="color: #002200;">:</span>NSUTF8StringEncoding<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request setDelegate<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request setDidFinishSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>requestFinished<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request setDidFailSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>requestFailed<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request startAsynchronous<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>Then you implement your delegate selector as in 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
</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> requestFinished<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>ASIHTTPRequest <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>request
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>response <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>request responseString<span style="color: #002200;">&#93;</span>;
    <span style="color: #11740a; font-style: italic;">// response contains the data returned from the server.</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> requestFailed<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>ASIHTTPRequest <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>request
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>request error<span style="color: #002200;">&#93;</span>;
    <span style="color: #11740a; font-style: italic;">// Do something with the error.</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Similarly, if you want to submit data to a form like we did earlier using the NSURLConnection/NSURLRequest combination, we can instead use the ASIFormDataRequest class.</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;">ASIFormDataRequest <span style="color: #002200;">*</span>request <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>ASIFormDataRequest requestWithURL<span style="color: #002200;">:</span>url<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request setPostValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;1&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;go&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request setPostValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Bad%20Bad%20Bug&quot;</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>request setPostValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;This%20bug%20is%20really%20really%20super%20bad.&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;description&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request setDidFinishSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>requestFinished<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request setDidFailSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>requestFailed<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>request startAsynchronous<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>When this request completes, we will have the formatted HTML in the responseString of the ASIHTTPRequest object:</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><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> requestFinished<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>ASIHTTPRequest <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>request
<span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>response <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>request responseString<span style="color: #002200;">&#93;</span>;
    <span style="color: #11740a; font-style: italic;">// response contains the HTML response from the form.</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>I have come to prefer using ASIHTTPRequest for network access, however, this is a matter of taste. It is a very clean and well written library of classes, so I highly recommend it, but your mileage may vary.</p>

<h2>So What About REST?</h2>

<p>As I said at the beginning, I&#8217;m not going to go into a lot of detail about how to set up a REST web service as implementation of the <a href="http://www.xfront.com/REST-Web-Services.html">REST philosophy</a> is really up to the developer. However, here are a few points about how I go about it:</p>

<ul>
<li><strong>Create individual server side scripts for each of the functions you want to implement.</strong> Instead of creating one master script, create one for each function you want to implement. This helps you maintain the code as when you need to update or fix something, it can be very targted.</li><br />
<li><strong>Make heavy use of mod_rewrite in your Apache server.</strong> Just use Apache. If you&#8217;re using something else, I&#8217;m sorry but you&#8217;re on your own. The rewrite mechanism that mod_rewrite provides enables you to take difficult to read URLs and make them easy to understand. WordPress, which we use for this blog, changes a URL that looks like this http://www.cimgf.com/?p=235, into something that looks like this: http://www.cimgf.com/2010/01/28/fun-with-uibuttons-and-core-animation-layers/ using mod_rewrite .
<br /><br />
It also so happens to provide a great way to implement a REST web service. Say you want to look up a bug by it&#8217;s unique ID in a bug tracker database. Your request would normally look like this http://www.cimgf.com/showbug.php?id=1234. The mod_rewrite module allows you to define rewrite rules that would change this URL to http://www.cimgf.com/bugs/1234. The rule to do this is very simple.


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;">RewriteEngine On
RewriteRule ^bugs<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #7a0874; font-weight: bold;">&#91;</span>:alnum:<span style="color: #7a0874; font-weight: bold;">&#93;</span><span style="color: #7a0874; font-weight: bold;">&#93;</span>+<span style="color: #7a0874; font-weight: bold;">&#41;</span>$ <span style="color: #000000; font-weight: bold;">/</span>showbug.php?<span style="color: #007800;">id</span>=<span style="color: #007800;">$1</span></pre></td></tr></table></div>



The RewriteRule line uses a regular expression to define how to translate from the uglier URL to the pretty one. This regex means the following: &#8220;look for the word <em>bugs</em> at the beginning of the parameters string, followed by a forward slash, followed by one or more numbers until you reach the end of the line.&#8221; Notice the $1 in the second section. If you are not familiar with perl compatible regular expressions, this simply means use whatever was found between the parens in the regex. In our case the parens are &#8220;capturing&#8221; the ID of the bug the user is requesting. The rewrite rule is then passing that along to the real <em>showbug.php</em> script.
<br /><br />
You just add this to the <strong>.htaccess</strong> file in the directory where you are hosting your server side scripts and you will be able to load the load your data using the REST looking URL&#8211;assuming of course your Apache web server has mod_rewrite enabled. Even if you are using shared hosting, there is no excuse for a web host not to have this enabled. If it is not enabled, you need to find a new web host.
</li><br />
<li><strong>Drive your web service with a scripted backend that connects to a commodity database like MySQL.</strong> Sanity check all of the input you get from your user by looking for vulnerabilities such as SQL injection attacks, but then insert the data into the database using standard SQL calls. If you receive the data, as XML for example, you can simply parse the XML into a DOM object and insert it from there. Better yet, use a (PHP) server side module that converts from XML to SQL for you.</li><br />
<li><strong>Use a framework like Rails.</strong> Most of the folks I know who have used it have nothing to say but good about implementing web services using Ruby on Rails. I can&#8217;t recommend it personally, but people I respect swear by it. It handles a lot of the heavy lifting of developing a web service by constructing the underlying functionality for you after you have specified basic meta data that defines the entities you want to manage.<br /><br />
The down side of this option for me is that I need to learn yet another programming language, Ruby. While I&#8217;m getting around to it, it hasn&#8217;t been on the top of my priority list.</li><br />
<li><strong>Use S3 for Assets.</strong> This is simply a suggestion, however, I think it’s a good one. If all you need is to access assets from your iPhone app, keep a structured data document around, like an XML document in your S3 bucket. Let it map out where the assets are stored in your S3 buckets. Then all you have to do is maintain that one XML document and upload a new one each time your content needs to change. It will define for your app where the various assets are located along with any other information you might want to provide about that asset.
</ul>

<h2>Conclusion</h2>

<p>Networking code has gotten much simpler to implement in recent years, so accessing your resources in the cloud is a great solution to many application development problems. There are some great tools out there these days regardless of whether you are developing the client or the server. If you need to access the cloud, use the various libraries available to you and keep your designs simple. Doing so will yield great results.</p>

<p>If you have some suggestions for how to implement REST web services for iPhone apps, leave them in the comments section below. Remember that all comments are moderated, so if you don&#8217;t see your comment appear right away, just be patient. We&#8217;ll approve it as soon as possible. Until next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2010/02/12/accessing-the-cloud-from-cocoa-touch/feed/</wfw:commentRss>
		<slash:comments>13</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>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>UITableViewCell Dynamic Height</title>
		<link>http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/</link>
		<comments>http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 05:35:58 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<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=732</guid>
		<description><![CDATA[At first glance setting a height dynamically for table view cells seems a little daunting and the first most obvious answers that come to mind are not necessarily correct. In this post I will show you how to set your table view cell heights dynamically based upon the text content without subclassing UITableViewCell. You can [...]]]></description>
			<content:encoded><![CDATA[<p>At first glance setting a height dynamically for table view cells seems a little daunting and the first most obvious answers that come to mind are not necessarily correct. In this post I will show you how to set your table view cell heights dynamically based upon the text content without subclassing UITableViewCell. You can subclass it, however, doing so does not make the code much cleaner as setting the height is done in your delegate for the table view itself rather than the cell anyhow. Read on to see what you need to know to make dynamic cell height sizing a breeze.
<span id="more-732"></span>
There are probably numerous reasons why you might want dynamic heights for your table view cells, but the one I&#8217;ve run into most is the need to resize because I am displaying lists of text objects with varying lengths. When the text is short, it might fit in the normal cell label, however, if the text gets longer, you will want to resize the cell so that you can display the complete content. I&#8217;ve distilled the process of resizing table cells to a few rules of thumb. Here they are:</p>

<ul>
<p><li>Create, configure, and add a <strong>UILabel</strong> as a subview of the <i>contentView</i> in the cell.</p>
<p><li>Calculate the height in the UITableView delegate method, &#8211; (CGFloat)tableView:(UITableView*)tableView <strong>heightForRowAtIndexPath</strong>:(NSIndexPath *)indexPath;</li></p>
<p><li>Calculate the frame for the UILabel in the UITableView delegate method, &#8211; (UITableViewCell*)tableView:(UITableView*)tableView <strong>cellForRowAtIndexPath</strong>:(NSIndexPath *)indexPath;</li></p>
</ul>

<p>I am going to cover each of these rules in detail, but take a look at the output of the example project in the screenshot.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2009/09/dynamicheights.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/09/dynamicheights.png" alt="Dynamic Heights" title="Dynamic Heights" class="alignleft size-full wp-image-737" /></a></p>

<h2>Add a UILabel to the Cell</h2>

<p>In simpler table view based applications, you can simply set the text of the table view cell&#8217;s text label like this:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>cell textLabel<span style="color: #002200;">&#93;</span> setText<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Text for the current cell here.&quot;</span><span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>Doing so might make you think that you can manipulate the UILabel that the cell uses, however, I&#8217;ve found my attempts to change the UILabel&#8217;s frame get ignored completely, so it is not a good candidate for use with our dynamic resizing code.</p>

<p>Instead what we need to do is programatically create a UILabel and add it to the cell&#8217;s content view. Do this in the call to -cellForRowAtIndexPath. Use something like 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
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>UITableViewCell <span style="color: #002200;">*</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>tv cellForRowAtIndexPath<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>
  UITableViewCell <span style="color: #002200;">*</span>cell;
  UILabel <span style="color: #002200;">*</span>label <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
  cell <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>tv dequeueReusableCellWithIdentifier<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Cell&quot;</span><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> initWithFrame<span style="color: #002200;">:</span>CGRectZero 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>;
&nbsp;
    label <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UILabel alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span>CGRectZero<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>label setLineBreakMode<span style="color: #002200;">:</span>UILineBreakModeWordWrap<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>label setMinimumFontSize<span style="color: #002200;">:</span>FONT_SIZE<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>label setNumberOfLines<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>label setFont<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>UIFont systemFontOfSize<span style="color: #002200;">:</span>FONT_SIZE<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>label setTag<span style="color: #002200;">:</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>cell contentView<span style="color: #002200;">&#93;</span> addSubview<span style="color: #002200;">:</span>label<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>This is not the completed code as you&#8217;ll notice that we have initialized the label only when the cell needs created for the first time, that is if (cell == nil) after a call to -dequeueReusableCellWithIdentifier. There are two points I want to address in relation to this. First, notice the label has a <strong>tag</strong> associated with it after a call to -setTag:1. This will be used in the case where the cell is not equal to nil after a call to -dequeueReusableCellWithIdentifier. In that case we will need to get a handle to the label by calling [cell viewWithTag:1] which will return the view that we associated with that tag. Second, notice that we have added our label to the cell&#8217;s content view with a call to [[cell contentView] addSubview:label]. This is done when the label is initialized and should only be done once. Adding it each time this method is called will add the label again to the subviews array. We will come back to this code to finish it in a minute, but first let&#8217;s take a look at how we can set the height for our cell now that our label has been added.</p>

<h2>Calculate the Cell Height</h2>

<p>In a complex cell, your calculations could get a bit challenging, however, you only need to worry with the items that will change in height. In our example, the only item you need to deal with is the label that we added. We calculate the height of the cell by determining the size of the text based on the length of the text and the font we intend to use. The <strong>NSString</strong> class provides a method called -sizeWithFont that enables us to obtain this size. The following code show how we implement our call to -heightForRowAtIndexPath:</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: #002200;">-</span> <span style="color: #002200;">&#40;</span>CGFloat<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 heightForRowAtIndexPath<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: #400080;">NSString</span> <span style="color: #002200;">*</span>text <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>items objectAtIndex<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>indexPath row<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  CGSize constraint <span style="color: #002200;">=</span> CGSizeMake<span style="color: #002200;">&#40;</span>CELL_CONTENT_WIDTH <span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>CELL_CONTENT_MARGIN <span style="color: #002200;">*</span> <span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span>, 20000.0f<span style="color: #002200;">&#41;</span>;
&nbsp;
  CGSize size <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>text sizeWithFont<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>UIFont systemFontOfSize<span style="color: #002200;">:</span>FONT_SIZE<span style="color: #002200;">&#93;</span> constrainedToSize<span style="color: #002200;">:</span>constraint lineBreakMode<span style="color: #002200;">:</span>UILineBreakModeWordWrap<span style="color: #002200;">&#93;</span>;
&nbsp;
  CGFloat height <span style="color: #002200;">=</span> MAX<span style="color: #002200;">&#40;</span>size.height, 44.0f<span style="color: #002200;">&#41;</span>;
&nbsp;
  <span style="color: #a61390;">return</span> height <span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span>CELL_CONTENT_MARGIN <span style="color: #002200;">*</span> <span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>You will notice that we have several constants we are using to calculate the size of our cell. These are defined as follows:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#define FONT_SIZE 14.0f</span>
<span style="color: #6e371a;">#define CELL_CONTENT_WIDTH 320.0f</span>
<span style="color: #6e371a;">#define CELL_CONTENT_MARGIN 10.0f</span></pre></td></tr></table></div>


<p>The constant <strong>CELL_CONTENT_WIDTH</strong> is the width of the entire cell. <strong>CELL_CONTENT_MARGIN</strong> is the margin we want to use all the way around the cell as the content inset, and of course <strong>FONT_SIZE</strong> is the size of the font we want to use for the label text.</p>

<p>The first place we use these is to create a constraint with the content width. Notice that CGSizeMake takes as its first parameter the total content width minus the margin times 2. This subtracts the margin from the left and the margin from the right from the total width to have the actual width of the label. The second parameter is just a maximum number we provide. The call to -sizeWithFont will set this to the actual height in the next line. This call to -sizeWithFont calculates the size according to the constant UILineBreakModeWordWrap which causes it to return the correct size for word wrap&#8211;which is why the width is important to get right. Next we set our height for the cell using a call to the MAX macro. This will ensure that our cell height will never be shorter than the default 44 pixels as MAX returns the larger of the two variables. Finally, we add our margin height back into the height for both top and bottom (hence x 2) and then return the result.</p>

<p>To help visualize how the margin is working, take a look at the following screenshot to see what each label looks like with a border around it. Turning this on with a call to [[label layer] setBorderWidth:2.0f] on the UILabel we added in the previous section makes it clear where the margins are.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2009/09/dynamicheights02.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/09/dynamicheights02.png" alt="Dynamic Heights Outline" title="Dynamic Heights Outline" class="alignleft size-full wp-image-744" /></a></p>

<h2>Calculate the UILabel Frame and Set It</h2>

<p>The same calculation we used to determine the height in the previous section is the code we use to set the frame for the UILabel we added in the beginning. To complete this tutorial we will finish out our implementation of -cellForRowAtIndexPath with 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
31
32
33
34
35
36
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>UITableViewCell <span style="color: #002200;">*</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>tv cellForRowAtIndexPath<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>
  UITableViewCell <span style="color: #002200;">*</span>cell;
  UILabel <span style="color: #002200;">*</span>label <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
  cell <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>tv dequeueReusableCellWithIdentifier<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Cell&quot;</span><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> initWithFrame<span style="color: #002200;">:</span>CGRectZero 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>;
&nbsp;
    label <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UILabel alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span>CGRectZero<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>label setLineBreakMode<span style="color: #002200;">:</span>UILineBreakModeWordWrap<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>label setMinimumFontSize<span style="color: #002200;">:</span>FONT_SIZE<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>label setNumberOfLines<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>label setFont<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>UIFont systemFontOfSize<span style="color: #002200;">:</span>FONT_SIZE<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>label setTag<span style="color: #002200;">:</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>label layer<span style="color: #002200;">&#93;</span> setBorderWidth<span style="color: #002200;">:</span>2.0f<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>cell contentView<span style="color: #002200;">&#93;</span> addSubview<span style="color: #002200;">:</span>label<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>text <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>items objectAtIndex<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>indexPath row<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  CGSize constraint <span style="color: #002200;">=</span> CGSizeMake<span style="color: #002200;">&#40;</span>CELL_CONTENT_WIDTH <span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>CELL_CONTENT_MARGIN <span style="color: #002200;">*</span> <span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span>, 20000.0f<span style="color: #002200;">&#41;</span>;
&nbsp;
  CGSize size <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>text sizeWithFont<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>UIFont systemFontOfSize<span style="color: #002200;">:</span>FONT_SIZE<span style="color: #002200;">&#93;</span> constrainedToSize<span style="color: #002200;">:</span>constraint lineBreakMode<span style="color: #002200;">:</span>UILineBreakModeWordWrap<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>label<span style="color: #002200;">&#41;</span>
    label <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>UILabel<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span>cell viewWithTag<span style="color: #002200;">:</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>label setText<span style="color: #002200;">:</span>text<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>label setFrame<span style="color: #002200;">:</span>CGRectMake<span style="color: #002200;">&#40;</span>CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH <span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>CELL_CONTENT_MARGIN <span style="color: #002200;">*</span> <span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span>, MAX<span style="color: #002200;">&#40;</span>size.height, 44.0f<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #a61390;">return</span> cell;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Just remember that anything done within the if (cell == nil) block is initialization code and should only be done when the cell is first created. Anything done outside of the block will be used every time the -cellForRowAtIndexPath is called, which is any time the data gets reloaded or the view gets scrolled.</p>

<p>That being said, you will see that the only thing we do every time it gets called is setting the text of the current item and setting the label&#8217;s frame for the current item (lines 32 and 33). Notice that we got a handle to our UILabel by calling [cell viewWithTag:1] (lines 29 and 30) in the case where the label is nil in subsequent/non-initialization calls to this method. You will notice that our frame calculation code is exactly the same as what we used in the previous section to determine the row height.</p>

<h2>Conclusion</h2>

<p>Calculating dynamic cell heights is really not too hard. If you have a very complex cell, just remember that all you really need to calculate is the height based up a width that shouldn&#8217;t change and the size of the text of a certain font (unless of course you support both portrait and landscape modes&#8211;which makes things a little more challenging. I will, however, leave this as an exercise for the reader). If you find yourself wondering where your actual frame is displaying for a given view, just turn on the view border by calling [[view layer] setBorderWidth:2.0f]. This will help you see what is going on and give you the ability get to the bottom of your display problems quicker. Until next time.</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2009/08/DynamicHeights.zip'>DynamicHeights Demo Project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>UITabBarController with UINavigationController Using Interface Builder</title>
		<link>http://www.cimgf.com/2009/06/25/uitabbarcontroller-with-uinavigationcontroller-using-interface-builder/</link>
		<comments>http://www.cimgf.com/2009/06/25/uitabbarcontroller-with-uinavigationcontroller-using-interface-builder/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 03:18:52 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<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=590</guid>
		<description><![CDATA[I&#8217;ve seen a good bit of sample code that shows how to implement using a UINavigationController in a view controller that is managed by a UITabBarController, but I haven&#8217;t seen much on how to do it with Interface Builder. Turns out that it&#8217;s pretty simple and I&#8217;m going to show you how. TabBarNavigator Demo Project [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve seen a good bit of sample code that shows how to implement using a UINavigationController in a view controller that is managed by a UITabBarController, but I haven&#8217;t seen much on how to do it with Interface Builder. Turns out that it&#8217;s pretty simple and I&#8217;m going to show you how.
<span id="more-590"></span></p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2009/06/tabbarnavigator.zip'>TabBarNavigator Demo Project</a></p>

<p>To get started, create a new project in Xcode. Select the <em>Tab Bar Application</em> template and click <em>Choose&#8230;</em>.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2009/06/newproject.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/06/newprojectsmall.png" alt="newprojectsmall" title="newprojectsmall" width="384" height="308" class="alignnone size-full wp-image-599" /></a></p>

<p>Name the project, TabBarNavigator and click <em>Save</em></p>

<div id="attachment_596" class="wp-caption alignnone" style="width: 310px"><a href="http://www.cimgf.com/wp-content/uploads/2009/06/tabbarnavigator.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/06/tabbarnavigator-300x221.png" alt="TabBarNavigator Project" title="TabBarNavigator Project" width="300" height="221" class="size-medium wp-image-596" /></a><p class="wp-caption-text">TabBarNavigator Project</p></div>

<h2>Change The Controller Type</h2>

<ol>
<li><p>In Xcode, expand the <em>Resources</em> group in the <em>Groups and Files</em> view and double-click <em>MainWindow.xib</em> to open the xib in Interface Builder</p></li>

<li><p>When Interface builder opens, change the xib <em>View Mode</em> to the tree view mode and expand your <em>Tab Bar Controller</em> item.
<a href="http://www.cimgf.com/wp-content/uploads/2009/06/mainwindow.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/06/mainwindow-300x213.png" alt="MainWindow.xib" title="MainWindow.xib" width="300" height="213" class="alignnone size-medium wp-image-602" /></a>
</p></li>

<li><p>Make sure that the <em>Tab View Controller</em> object is selected. In the object inspector switch to the <em>Attributes</em> tab and change the <em>Class</em> for the <em>First</em> controller from <em>View Controller</em> to <em>Navigation Controller</em>.
<a href="http://www.cimgf.com/wp-content/uploads/2009/06/navcontrollerselect.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/06/navcontrollerselect-218x300.png" alt="Select Navigation Controller" title="Select Navigation Controller" width="218" height="300" class="alignnone size-medium wp-image-603" /></a>
</p></li>

<li><p>You will notice back in the <em>MainWindow.xib</em> window that the view controller for <em>First View</em> is now a <em>UINavigationController</em>. Expand the UINavigationController item now.
<a href="http://www.cimgf.com/wp-content/uploads/2009/06/mainwindow2.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/06/mainwindow2-300x213.png" alt="New UINavigationController" title="New UINavigationController" width="300" height="213" class="alignnone size-medium wp-image-604" /></a></p></li>

<li><p>Now select the <em>View Controller</em> that is a child of our new <em>UINavigationController</em>. Click on the <em>Identity</em> tab of the object inspector and change the <em>Class</em> to <em>FirstViewController</em>.
<a href="http://www.cimgf.com/wp-content/uploads/2009/06/identity.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/06/identity.png" alt="First View Controller Identity" title="First View Controller Identity" width="236" height="285" class="alignnone size-full wp-image-611" /></a></p></li>

<li><p>Click on the <em>Navigation Item</em> that is a child of the <em>First View Controller</em> and change the <em>Title</em> in the <em>Attributes</em> tab of the object inspector to <em>&#8220;First&#8221;</em>.
<a href="http://www.cimgf.com/wp-content/uploads/2009/06/navitemattributes.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/06/navitemattributes.png" alt="Navigation Item Attributes" title="Navigation Item Attributes" width="236" height="142" class="alignnone size-full wp-image-613" /></a></p>
</li>

<li><p>Save your changes in Interface Builder, switch back to Xcode and <em>Build &amp; Go</em>. You should see something like the following in your <em>First</em> view tab.
<a href="http://www.cimgf.com/wp-content/uploads/2009/06/firstviewsimulator.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/06/firstviewsimulator-161x300.png" alt="First View in Simulator" title="First View in Simulator" width="161" height="300" class="alignnone size-medium wp-image-615" /></a></p>
</li>

<li><p>Notice that there is a Toolbar visible at the bottom of the first view. If you would like to hide this, go back into Interface Builder and select the <em>Navigation Controller</em> In the object inspector, uncheck the <em>Shows Toolbar</em> checkbox.
<a href="http://www.cimgf.com/wp-content/uploads/2009/06/uncheckshowstoolbar.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/06/uncheckshowstoolbar.png" alt="Uncheck Shows Toolbar" title="Uncheck Shows Toolbar" width="236" height="201" class="alignnone size-full wp-image-617" /></a></p>
</li>
</ol>

<h2>Pushing a New Controller</h2>

<p>Before we create a new view controller, let&#8217;s set up our <em>FirstViewController</em> to create an event that will trigger pushing the new controller. Since our FirstView was not created with a xib, let&#8217;s create one and then add actions and outlets to it.</p>

<ol>
<li><p>In Xcode, right-click or ctrl-click the <em>Resources</em> group and select <em>Add | New File&#8230;</em>. In the ensuing dialog, select <em>View XIB</em> in the <em>User Interface</em> section of <em>iPhone OS</em> templates and click <em>Next</em>. Name the XIB <em>FirstView</em> and click <em>Finish</em>.</p></li>

<li><p>Double-click the new XIB to open it in Interface Builder and select the <em>Identity</em> tab after you have made sure that <em>File&#8217;s Owner</em> is selected. Change the <em>Class</em> field to <em>FirstViewController</em>.</p>
</li>

<li><p>Ctrl-click and drag a connection from the <em>File&#8217;s Owner</em> object to the <em>View</em> object in the main window for our XIB and select <em>view</em> in the ensuing pop up menu.</p></li>

<li><p>From the <em>Object Library</em> drag and drop a button onto the view. Double-click the button and give it the title <em>&#8220;Push&#8221;</em>. Save your changes in Interface Builder and switch back to Xcode.
<a href="http://www.cimgf.com/wp-content/uploads/2009/06/pbutton.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/06/pbutton-161x300.png" alt="&quot;Push&quot; Button" title="&quot;Push&quot; Button" width="161" height="300" class="alignnone size-medium wp-image-633" /></a>
</p>
</li>

<li><p>Open the file <em>FirstViewController.h</em> and add an action so that the header looks like this:


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &lt;UIKit/UIKit.h&gt;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> FirstViewController <span style="color: #002200;">:</span> UIViewController <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>IBAction<span style="color: #002200;">&#41;</span>push<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></td></tr></table></div>



</p>
</li>

<li><p>Open the file <em>FirstViewController.m</em> and implement the action so that the code looks like this:


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;FirstViewController.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> FirstViewController
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>push<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>
&nbsp;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>dealloc <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>



<blockquote><strong>Note:</strong> You can safely delete all of the view controller template code which I have done in this example. Don&#8217;t worry. You won&#8217;t hurt anything.</blockquote></p>
</li>
</ol>

<p>We will come back to the push implementation after we have created our new view controller that we are going to push.</p>

<h2>Create the New View Controller</h2>

<p>We are now going to create the new view controller that will be displayed when we tap our &#8220;Push&#8221; button in the <em>FirstViewController</em>.</p>

<ol>
<li><p>In Xcode, right-click or ctrl-click the <em>Classes</em> group and select <em>Add | New File&#8230;</em>. In the ensuing dialog, select <em>UIViewController subclass</em> in the <em>Cocoa Touch Class</em> category of the <em>iPhone OS</em> templates. Make sure <em>With XIB for user interface</em> is checked and click <em>Next</em>. Name the file <em>NewViewController.m</em> and click <em>Finish</em>.</p></li>

<li><p>For organization purposes, move the newly created <em>NewViewController.xib</em> file into the <em>Resources</em> group. Then double-click it to open it in Interface Builder.</p></li>

<li><p>In Interface Builder, drag a <em>UILabel</em> onto the view and give it the title <em>&#8220;New View Controller&#8221;</em>. Save the file and switch back to Xcode.</p></li>

<li><p>Open the file <em>FirstViewController.m</em> again and implement controller push code so that it looks like this:


<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: #6e371a;">#import &quot;FirstViewController.h&quot;</span>
<span style="color: #6e371a;">#import &quot;NewViewController.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> FirstViewController
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>push<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>
  NewViewController <span style="color: #002200;">*</span>controller <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NewViewController alloc<span style="color: #002200;">&#93;</span> initWithNibName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;NewViewController&quot;</span> bundle<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self navigationController<span style="color: #002200;">&#93;</span> pushViewController<span style="color: #002200;">:</span>controller animated<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>controller release<span style="color: #002200;">&#93;</span>, controller <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>dealloc <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>



<blockquote>Don&#8217;t forget to #import &#8220;NewViewController.h&#8221;</blockquote></p>
</li>

<li><p>To connect our button to the push action, double-click the <em>FirstView.xib</em> file in the <em>Resources</em> group to open it in Interface Builder.</p></li>

<li><p>Ctrl-click and drag a connection from the <em>&#8220;Push&#8221;</em> button in our view to the <em>File&#8217;s Owner</em> object and select <em>push:</em> in the ensuing pop up menu. Save your changes in Interface Builder. Switch back to Xcode and <em>Build &amp; Go</em>.</p></li>

<li><p>Additionally, you can give your <em>New View Controller</em> a title by implementing <em>-viewDidLoad</em>. Just open your <em>NewViewController.m</em> file and uncomment the <em>-viewDidLoad</em> code making it look like the following:


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;NewViewController.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> NewViewController
&nbsp;
<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>self setTitle<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;New View&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>super viewDidLoad<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>dealloc <span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>



</p>
</li>
</ol>

<p><a href="http://www.cimgf.com/wp-content/uploads/2009/06/newview.png" rel="lightbox"><img src="http://www.cimgf.com/wp-content/uploads/2009/06/newview-161x300.png" alt="New View Controller" title="New View Controller" width="161" height="300" class="alignnone size-medium wp-image-630" /></a></p>

<p>And that&#8217;s pretty much all there is to it. There are a lot of steps here, but I think you&#8217;ll see that setting up your application to implement both a UITabBarController and a UINavigationController is pretty straight forward.</p>

<h2>Conclusion</h2>

<p>How best to organize your views in an iPhone application is a design process. Often applications will have a lot of data for your users to access and it will be up to you to find the best way to organize it. Being able to utilize both a tab bar and a navigation controller can really help in this process. Until next time.</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2009/06/tabbarnavigator.zip'>TabBarNavigator Demo Project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2009/06/25/uitabbarcontroller-with-uinavigationcontroller-using-interface-builder/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Magical iPhone View Controllers</title>
		<link>http://www.cimgf.com/2009/05/11/magical-iphone-view-controllers/</link>
		<comments>http://www.cimgf.com/2009/05/11/magical-iphone-view-controllers/#comments</comments>
		<pubDate>Mon, 11 May 2009 16:19:53 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Undocumented]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=531</guid>
		<description><![CDATA[Update: This is documented behavior. Every now and again while doing development you stumble upon something that makes you go, hmmmm. Those are normally the moments at which you have to ask yourself, &#8220;is this a bug or a feature&#8221;. If it&#8217;s a bug, then you should file a radar with Apple, however, what if [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update: This is <a href="http://developer.apple.com/iPhone/library/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instm/UIViewController/initWithNibName:bundle:">documented behavior</a></strong>.</p>

<p>Every now and again while doing development you stumble upon something that makes you go, hmmmm. Those are normally the moments at which you have to ask yourself, &#8220;is this a bug or a feature&#8221;. If it&#8217;s a bug, then you should file a radar with Apple, however, what if it&#8217;s a feature? You blog about it, of course!</p>

<p>I have done a bit less iPhone development than Marcus, so he was a little stumped while looking through some of my code where I created a view controller using a simple alloc/init. Most interestingly is that fact that the app works. It loads the correct nib and displays the view just fine without any trouble. Notice I said alloc/init and not alloc/initWithNibName. How can this possibly work? How did my controller &#8220;know&#8221; which view to use?
<span id="more-531"></span></p>

<p>Well, the answer is pretty simple, but not immediately obvious. I could try to act like I meant to use an undocumented feature because I&#8217;m just that cool, but the fact of the matter is I was in band. Marching band, even. Band people aren&#8217;t cool. Though the color guard thought we were cool. But I digress. I just inadvertently added the alloc/init code without thinking and never looked back since the view loaded and displayed just fine. After renaming the nib/xib in the project and in doing so causing the view to fail to load properly we were able to determine that there must be some underlying <em>feature</em> of view controllers where it will automagically look for a view based upon its own name.</p>

<h2>Say Huh?</h2>

<p>Yep. That&#8217;s correct. If you create a view controller with the name <em>MySpiffyViewController</em>, for example, and instantiate it with alloc/init in your code, it will assume that the nib you want is actually called <em>MySpiffyView</em>. Spiffy eh? Some people may call this a bug, but the fact that it works this way shows that it was intentional. Now, I recommend that you steer clear of intentionally creating your view controllers this way as Apple may decide it&#8217;s a bug after all and change (fix?) it in a future release. It is however an interesting undocumented feature at the moment.</p>

<h2>You Can Duplicate It</h2>

<p>Here are the steps if you want to try this yourself. Of course, you can just <a href="#example">download the example project below</a> if you don&#8217;t want to go through the steps.</p>

<ol>
<li>In Xcode, press Command+Shift+N to open the New Project templates and select <strong>View-based Application</strong> in the <strong>iPhone OS</strong> category and click <strong>Choose&#8230;</strong>.</li>
<br />
<li>Name the project <strong>SpiffyView</strong> and click <strong>Save</strong></li>
<br />
<li>The first thing we need to do is change our code in the app delegate (called SpiffyViewAppDelegate.m) to add a UINavigationController.


<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><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>applicationDidFinishLaunching<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIApplication <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>application <span style="color: #002200;">&#123;</span>    
    UINavigationController <span style="color: #002200;">*</span>navController <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UINavigationController alloc<span style="color: #002200;">&#93;</span> initWithRootViewController<span style="color: #002200;">:</span>viewController<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>navController navigationBar<span style="color: #002200;">&#93;</span> setBarStyle<span style="color: #002200;">:</span>UIBarStyleBlackTranslucent<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>window addSubview<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>navController view<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>window makeKeyAndVisible<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>



This will enable us to navigate to the new view we create next.
</li>
<br />
<li>Press Command+N and select <strong>View XIB</strong> under the <strong>User Interfaces</strong> category. Click <strong>Next</strong>. Name the file <strong>MySpiffyView</strong> and click <strong>Finish</strong></li>
<br />
<li>Press Command+N again and select <strong>UIViewController subclass</strong> under the <strong>Cocoa Touch Classes</strong> category. Click <strong>Next</strong>. Name the file <strong>MySpiffyViewController.m</strong> and click <strong>Finish</strong>.</li>
<br />
<li>Next we need to create an action in the view controller created by the project template called SpiffyViewViewController. Add the following code to the respective .m and .h files as follows.


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Add this to your SpiffyViewViewController.h</span>
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>showSpiffyView<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: #11740a; font-style: italic;">// Add this to your SpiffyViewViewController.m. Make sure you #import &quot;MySpiffyViewController.h&quot; as well.</span>
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>showSpiffyView<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;">id</span> controller <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>MySpiffyViewController alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self navigationController<span style="color: #002200;">&#93;</span> pushViewController<span style="color: #002200;">:</span>controller animated<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>controller release<span style="color: #002200;">&#93;</span>, controller <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


</li>
<br />
<li>Now we need to connect a button to the action. In your project under resources, double-click SpiffyViewViewController.xib to open it in Interface Builder.</li>
<br />
<li>In Interface Builder, drag a button onto the view and change its text to &#8220;Spiffy View&#8221;</li>
<br />
<li>Now, Control-Click and drag a connection from your button in the view, to the <strong>File&#8217;s Owner</strong> and select <strong>showSpiffyView:</strong> in the ensuing menu. Save the file in IB.</li>
<br />
<li>Now, back in Xcode, double click MySpiffyView.xib to open it in Inteface Builder.</li>
<br />
<li>Change the <strong>File&#8217;s Owner</strong> class to MySpiffyViewController in the <strong>Identity</strong> tab of the <strong>Inspector</strong>.</li>
<br />
<li>Drag a label onto the view. Double click it to edit it and change the text to &#8220;This is the super spiffy view.&#8221; Save the file in IB.</li>
<br />
<li>Everything should be hooked up now. Go back to Xcode and &#8220;Build &amp; Go&#8221;. Your app should load in the simulator. When you see the &#8220;Spiffy View&#8221; button, click it and it should show your new view!!</li>
<br />
</ol>

<h2>Conclusion</h2>

<p>So how is that working? The only answer is there must be some underlying code that the view controller is using to locate its nib. Remember, we never told our controller what nib to use. We simply called alloc/init and voila, it works!!</p>

<p>If you think I ought to register this as a bug with Apple, let me know your thoughts in the comments. Oh and one other thing. I may have been in band, but I married a smokin&#8217; hot cheerleader. Take that all you cool people. ;-) Until next time.
<br /><br /><br />
<a name="example">
<a href='http://www.cimgf.com/wp-content/uploads/2009/05/spiffyview.zip'>Example Project SpiffyView.zip</a>
</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2009/05/11/magical-iphone-view-controllers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Record Your Core Animation Animation</title>
		<link>http://www.cimgf.com/2009/02/03/record-your-core-animation-animation/</link>
		<comments>http://www.cimgf.com/2009/02/03/record-your-core-animation-animation/#comments</comments>
		<pubDate>Tue, 03 Feb 2009 05:38:37 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[QTKit]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=437</guid>
		<description><![CDATA[Every once in a while I find a way to combine multiple technologies that, while they don&#8217;t produce anything terribly useful, are very interesting when combined. In this post I will be taking a look at combining Core Animation and QuickTime. As you may or may not be aware, you can draw in a graphics [...]]]></description>
			<content:encoded><![CDATA[<p>Every once in a while I find a way to combine multiple technologies that, while they don&#8217;t produce anything terribly useful, are very interesting when combined. In this post I will be taking a look at combining Core Animation and QuickTime. As you may or may not be aware, you can draw in a graphics context while your Core Animation animation is running and add each image created to a QTMovie object from QTKit. This enables you to create a QuickTime movie of your Core Animation animation. Here&#8217;s how.
<span id="more-437"></span></p>

<p>The basic process flow goes like this. Clicking the &#8216;Capture&#8217; button on the user interface calls an IBAction called <em>-saveAnimation</em>. It prompts the user to select an output file for the movie. When the user has selected the file, the animations are created and added to the layer. Next we create a timer that is going to call a function that will grab the current frame and place it into the QTMovie object using <em>-addImage</em> at a specified interval. We set our AppDelegate to also be the delegate for the animation group so that when the animation completes we get notified and can then write our QTMovie object data to disk.</p>

<h2>Use An Interesting Animation</h2>

<p>First you are going to need an animation that is worth recording. Of course any old animation will do, but we&#8217;ll keep it interesting by adding multiple animations to a single layer. I have created four different keyframe animations that we will add to an animation group. The keypaths are &#8220;backgroundColor&#8221;, &#8220;borderWidth&#8221;, &#8220;position&#8221;, and &#8220;bounds&#8221;. Check the sample code to see how these animations are constructed.</p>

<p>We set the duration for all of the animations to five seconds. We also need to make sure that we set the duration for the group itself, otherwise it will override the five second duration we set for the animations themselves and run in the default 0.25 seconds. The code below shows how the animations are added to the 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
</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>loadAnimations;
<span style="color: #002200;">&#123;</span>
  CAAnimationGroup <span style="color: #002200;">*</span>group <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CAAnimationGroup animation<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>group setAnimations<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>self backgroundColorAnimation<span style="color: #002200;">&#93;</span>,
                          <span style="color: #002200;">&#91;</span>self borderWidthAnimation<span style="color: #002200;">&#93;</span>,
                          <span style="color: #002200;">&#91;</span>self positionAnimation<span style="color: #002200;">&#93;</span>,
                          <span style="color: #002200;">&#91;</span>self boundsAnimation<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;
  <span style="color: #002200;">&#91;</span>group setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;mainGroup&quot;</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>group setDuration<span style="color: #002200;">:</span><span style="color: #2400d9;">5.0</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>group setAutoreverses<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>group setDelegate<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>layer addAnimation<span style="color: #002200;">:</span>group forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;group&quot;</span><span style="color: #002200;">&#93;</span>;  
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Notice that we have used KVC here to set a name for the animation group. We will use this as a tag later to make sure the animation that triggers our <em>-animationDidStop:finished</em> animation delegate is the correct one. More on that later.</p>

<h2>Get Our Movie Ready</h2>

<p>Prior to loading the animations, we prompt the user to select a file to write the movie file to. After loading the animations, we start our timer.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>saveAnimation<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;">NSSavePanel</span> <span style="color: #002200;">*</span>savePanel;
&nbsp;
  savePanel <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSSavePanel</span> savePanel<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>savePanel setExtensionHidden<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>savePanel setCanSelectHiddenExtension<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>savePanel setTreatsFilePackagesAsDirectories<span style="color: #002200;">:</span><span style="color: #a61390;">NO</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>savePanel runModal<span style="color: #002200;">&#93;</span> <span style="color: #002200;">==</span> NSOKButton <span style="color: #002200;">&#41;</span>
  <span style="color: #002200;">&#123;</span>
    movie <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>QTMovie alloc<span style="color: #002200;">&#93;</span> initToWritableFile<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>savePanel filename<span style="color: #002200;">&#93;</span> error<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;">&#91;</span>self loadAnimations<span style="color: #002200;">&#93;</span>;
&nbsp;
  timer <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSTimer</span> scheduledTimerWithTimeInterval<span style="color: #002200;">:</span><span style="color: #2400d9;">1.0</span><span style="color: #002200;">/</span><span style="color: #002200;">&#40;</span>NSTimeInterval<span style="color: #002200;">&#41;</span><span style="color: #2400d9;">10.0</span>
                                           target<span style="color: #002200;">:</span>self
                                         selector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>updateTime<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span>
                                         userInfo<span style="color: #002200;">:</span><span style="color: #a61390;">NULL</span>
                                          repeats<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;    
&nbsp;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Our <em>-updateTime</em> selector will get called every 1/10th of a second and will grab the current frame to save it to the QTMoive object. Here is the <em>-updateTime</em> code.</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>updateTime<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSTimer</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>theTimer;
<span style="color: #002200;">&#123;</span>
  <span style="color: #400080;">NSBitmapImageRep</span> <span style="color: #002200;">*</span>image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self getCurrentFrame<span style="color: #002200;">&#93;</span>;
&nbsp;
  QTTime <span style="color: #a61390;">time</span> <span style="color: #002200;">=</span> QTMakeTime<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1</span>, <span style="color: #2400d9;">10</span><span style="color: #002200;">&#41;</span>;
  <span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>attrs <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSDictionary</span> dictionaryWithObject<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;png &quot;</span> forKey<span style="color: #002200;">:</span>QTAddImageCodecType<span style="color: #002200;">&#93;</span>;
  <span style="color: #400080;">NSImage</span> <span style="color: #002200;">*</span>img <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>image TIFFRepresentation<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>movie addImage<span style="color: #002200;">:</span>img forDuration<span style="color: #002200;">:</span><span style="color: #a61390;">time</span> withAttributes<span style="color: #002200;">:</span>attrs<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>image release<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<h2>Obtaining the Current Frame</h2>

<p>The code to obtain the current frame is somewhat lengthy, but the concepts are pretty simple. We need to create a graphics context that we can draw into and then draw into it using the presentationLayer of the contenView&#8217;s root layer. If you&#8217;re not familiar, the presentationLayer provides the current state of the animated fields while &#8220;in-flight&#8221;.</p>

<p>Core Animation doesn&#8217;t provide any callbacks for when a frame is ready to be displayed which is why we are using a timer. This means that we may be capturing more frames than we need to, so getting the right frame rate takes a bit of trial and error, which I have to confess I wasn&#8217;t able to get nailed down completely. I&#8217;m still working on it and will update here when I get that part figured out. Meanwhile, here is the code for <em>-getCurrentFrame</em></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
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSBitmapImageRep</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>getCurrentFrame;
<span style="color: #002200;">&#123;</span>
  CGContextRef    context <span style="color: #002200;">=</span> <span style="color: #a61390;">NULL</span>;
  CGColorSpaceRef colorSpace;
  <span style="color: #a61390;">int</span> bitmapByteCount;
  <span style="color: #a61390;">int</span> bitmapBytesPerRow;
&nbsp;
  <span style="color: #a61390;">int</span> pixelsHigh <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span><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> bounds<span style="color: #002200;">&#93;</span>.size.height;
  <span style="color: #a61390;">int</span> pixelsWide <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span><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> bounds<span style="color: #002200;">&#93;</span>.size.width;
&nbsp;
  bitmapBytesPerRow   <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>pixelsWide <span style="color: #002200;">*</span> <span style="color: #2400d9;">4</span><span style="color: #002200;">&#41;</span>;
  bitmapByteCount     <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>bitmapBytesPerRow <span style="color: #002200;">*</span> pixelsHigh<span style="color: #002200;">&#41;</span>;
&nbsp;
  colorSpace <span style="color: #002200;">=</span> CGColorSpaceCreateWithName<span style="color: #002200;">&#40;</span>kCGColorSpaceGenericRGB<span style="color: #002200;">&#41;</span>;
&nbsp;
  context <span style="color: #002200;">=</span> CGBitmapContextCreate <span style="color: #002200;">&#40;</span><span style="color: #a61390;">NULL</span>,
                                   pixelsWide,
                                   pixelsHigh,
                                   <span style="color: #2400d9;">8</span>,
                                   bitmapBytesPerRow,
                                   colorSpace,
                                   kCGImageAlphaPremultipliedLast<span style="color: #002200;">&#41;</span>;
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>context<span style="color: #002200;">==</span> <span style="color: #a61390;">NULL</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;Failed to create context.&quot;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #a61390;">return</span> <span style="color: #a61390;">nil</span>;
  <span style="color: #002200;">&#125;</span>
&nbsp;
  CGColorSpaceRelease<span style="color: #002200;">&#40;</span> colorSpace <span style="color: #002200;">&#41;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span><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> presentationLayer<span style="color: #002200;">&#93;</span> renderInContext<span style="color: #002200;">:</span>context<span style="color: #002200;">&#93;</span>;
&nbsp;
  CGImageRef img <span style="color: #002200;">=</span> CGBitmapContextCreateImage<span style="color: #002200;">&#40;</span>context<span style="color: #002200;">&#41;</span>;
  <span style="color: #400080;">NSBitmapImageRep</span> <span style="color: #002200;">*</span>bitmap <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSBitmapImageRep</span> alloc<span style="color: #002200;">&#93;</span> initWithCGImage<span style="color: #002200;">:</span>img<span style="color: #002200;">&#93;</span>;
  CFRelease<span style="color: #002200;">&#40;</span>img<span style="color: #002200;">&#41;</span>;
&nbsp;
  <span style="color: #a61390;">return</span> bitmap;
&nbsp;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Notice that we are calling <em>-renderInContext</em> on the presentationLayer of the window&#8217;s contentView&#8217;s root layer. If we were only to render our animated layer, we wouldn&#8217;t be able to see the animation as it will only render the containing rectangle of the animating layer.</p>

<h2>Finishing Up</h2>

<p>Finally we need to write the movie data out to disk. The QTMovie object provides a single call to do so, but we need a way to know when the animation has finished so we can make this call. When we created our animation group, we set its delegate to our AppDelegate which will cause the delegate method <em>-animationDidStop:finished</em> to get called. Remember that setting the delegate for each of the individual animations gets ignored when you are using an animation group. We implement the <em>-animationDidStop:finished</em> delegate as shown below.</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: #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 stopped: %@&quot;</span>, theAnimation<span style="color: #002200;">&#41;</span>;
&nbsp;
  <span style="color: #a61390;">id</span> name <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>theAnimation valueForKey<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: #a61390;">if</span><span style="color: #002200;">&#40;</span> name <span style="color: #002200;">&#41;</span>
    <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span> <span style="color: #002200;">&#91;</span>name isEqualToString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;mainGroup&quot;</span><span style="color: #002200;">&#93;</span> <span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
      <span style="color: #002200;">&#91;</span>movie updateMovieFile<span style="color: #002200;">&#93;</span>;
      <span style="color: #002200;">&#91;</span>timer invalidate<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>The first thing we do is check the animation tag we set when creating the animation group. This really isn&#8217;t necessary in this code example since there is only one animation that is going to use it, but this code shows you how to differentiate if you were to use multiple animations or groups and wanted to know when each of them finished animating.</p>

<p>The call to <em>-updateMovieFile</em> writes the data to disk and we now have a QuickTime movie that will play our animation. Open the resulting file in QuickTime or just invoke QuickLook to see the result.</p>

<h2>Conclusion</h2>

<p>Maybe you can think of a use for this kind of thing. I haven&#8217;t yet&#8211;other than for writing a blog post of course. Shoot me your thoughts and comments in the comments section. Until next time.</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2009/02/caanimationcapture.zip'>CA Animation Capture Demo Project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2009/02/03/record-your-core-animation-animation/feed/</wfw:commentRss>
		<slash:comments>11</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>
	</channel>
</rss>

