<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Cocoa Is My Girlfriend &#187; Cocoa</title>
	<atom:link href="http://www.cimgf.com/category/cocoa/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cimgf.com</link>
	<description>Taglines are for Windows programmers</description>
	<lastBuildDate>Thu, 15 Jul 2010 21:20:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<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[Objective-C]]></category>
		<category><![CDATA[iPhone]]></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>4</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;">!</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>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2010/05/02/my-current-prefix-pch-file/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Creating a NSManagedObject that is Cross Platform</title>
		<link>http://www.cimgf.com/2010/02/18/creating-a-nsmanagedobject-that-is-cross-platform/</link>
		<comments>http://www.cimgf.com/2010/02/18/creating-a-nsmanagedobject-that-is-cross-platform/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 18:37:33 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>

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

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

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

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

<h2>NSImage vs UIImage</h2>

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

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

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

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

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

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

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

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


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


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

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


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#ifdef IPHONEOS_DEPLOYMENT_TARGET</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setImage<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIImage<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>self willChangeValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>data <span style="color: #002200;">=</span> UIImagePNGRepresentation<span style="color: #002200;">&#40;</span>image<span style="color: #002200;">&#41;</span>;
  <span style="color: #002200;">&#91;</span>myManagedObject setImage<span style="color: #002200;">:</span>data<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self setPrimitiveValue<span style="color: #002200;">:</span>data forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self didChangeValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>UIImage<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>self willAccessValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  UIImage <span style="color: #002200;">*</span>image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIImage imageWithData<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self primitiveValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self didAccessValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">return</span> image;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#else</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setImage<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSImage</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>self willChangeValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #400080;">NSBitmapImageRep</span> <span style="color: #002200;">*</span>bits <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>image representations<span style="color: #002200;">&#93;</span> objectAtIndex<span style="color: #002200;">:</span> <span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>data <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>bits representationUsingType<span style="color: #002200;">:</span>NSPNGFileType properties<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>myManagedObject setImage<span style="color: #002200;">:</span>data<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self setPrimitiveValue<span style="color: #002200;">:</span>data forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self didChangeValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSImage</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>self willAccessValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #400080;">NSImage</span> <span style="color: #002200;">*</span>image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSImage</span> alloc<span style="color: #002200;">&#93;</span> initWithData<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self primitiveValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self didAccessValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>image autorelease<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#endif</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>


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

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

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

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

<h2>Wrap Up</h2>

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

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

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

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

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

<p>Specifically this article walks through using the NSFetchedResultsController and some best practices in its use.  The magazine is available for free on their website, <a href="http://pragprog.com/magazines">The Pragmatic Bookshelf</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2010/01/09/the-pragpub-magazine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automatically save the dSYM files.</title>
		<link>http://www.cimgf.com/2009/12/23/automatically-save-the-dsym-files/</link>
		<comments>http://www.cimgf.com/2009/12/23/automatically-save-the-dsym-files/#comments</comments>
		<pubDate>Thu, 24 Dec 2009 02:28:50 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Development Environment]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Version Control]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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


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

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

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

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

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

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

<p>What makes it so is another little property of the CAShaperLayer called <strong>lineDashPhase</strong>. This property specifies the phase of the stroke pattern. The default is zero. Animate this property to see the marching ants effect. If you want the animation to loop perfectly, set the <strong>toValue</strong> in the animation to the sum of all of the values specified in the lineDashPattern array. The code to animate the lineDashPhase should look something like the following:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>toggleMarching<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender;
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>shapeLayer animationForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;linePhase&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
        <span style="color: #002200;">&#91;</span>shapeLayer removeAnimationForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;linePhase&quot;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
        CABasicAnimation <span style="color: #002200;">*</span>dashAnimation;
        dashAnimation <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CABasicAnimation 
                         animationWithKeyPath<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;lineDashPhase&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #002200;">&#91;</span>dashAnimation setFromValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithFloat<span style="color: #002200;">:</span>0.0f<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span>dashAnimation setToValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithFloat<span style="color: #002200;">:</span>15.0f<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span>dashAnimation setDuration<span style="color: #002200;">:</span>0.75f<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span>dashAnimation setRepeatCount<span style="color: #002200;">:</span><span style="color: #2400d9;">10000</span><span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #002200;">&#91;</span>shapeLayer addAnimation<span style="color: #002200;">:</span>dashAnimation forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;linePhase&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


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

<p>We set up our CAShaperLayer using the following code:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewDidLoad <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>super viewDidLoad<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// Create the shape layer</span>
    shapeLayer <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CAShapeLayer layer<span style="color: #002200;">&#93;</span>;
    CGRect shapeRect <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span>0.0f, 0.0f, 200.0f, 100.0f<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setBounds<span style="color: #002200;">:</span>shapeRect<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setPosition<span style="color: #002200;">:</span>CGPointMake<span style="color: #002200;">&#40;</span>160.0f, 140.0f<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setFillColor<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIColor clearColor<span style="color: #002200;">&#93;</span> CGColor<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setStrokeColor<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIColor blackColor<span style="color: #002200;">&#93;</span> CGColor<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setLineWidth<span style="color: #002200;">:</span>1.0f<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setLineJoin<span style="color: #002200;">:</span>kCALineJoinRound<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setLineDashPattern<span style="color: #002200;">:</span>
     <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithObjects<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithInt<span style="color: #002200;">:</span><span style="color: #2400d9;">10</span><span style="color: #002200;">&#93;</span>, 
      <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithInt<span style="color: #002200;">:</span><span style="color: #2400d9;">5</span><span style="color: #002200;">&#93;</span>, 
      <span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// Setup the path</span>
    CGMutablePathRef path <span style="color: #002200;">=</span> CGPathCreateMutable<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
    CGPathAddRect<span style="color: #002200;">&#40;</span>path, <span style="color: #a61390;">NULL</span>, shapeRect<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#91;</span>shapeLayer setPath<span style="color: #002200;">:</span>path<span style="color: #002200;">&#93;</span>;
    CGPathRelease<span style="color: #002200;">&#40;</span>path<span style="color: #002200;">&#41;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// Set the layer's contents</span>
    <span style="color: #002200;">&#91;</span>shapeLayer setContents<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIImage imageNamed<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;balloon.jpg&quot;</span><span style="color: #002200;">&#93;</span> CGImage<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self view<span style="color: #002200;">&#93;</span> layer<span style="color: #002200;">&#93;</span> addSublayer<span style="color: #002200;">:</span>shapeLayer<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


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

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

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

<h2>Conclusion</h2>

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

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

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


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


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

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

<p>Turns out that the modern way to disable sleep uses IOKit. Apple has <a href="http://developer.apple.com/mac/library/qa/qa2004/qa1340.html">a doc</a> for that too. Here is Listing 2:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &lt;IOKit/pwr_mgt/IOPMLib.h&gt;</span>
&nbsp;
...
<span style="color: #11740a; font-style: italic;">// kIOPMAssertionTypeNoDisplaySleep prevents display sleep,</span>
<span style="color: #11740a; font-style: italic;">// kIOPMAssertionTypeNoIdleSleep prevents idle sleep</span>
&nbsp;
IOPMAssertionID assertionID;
IOReturn success <span style="color: #002200;">=</span> IOPMAssertionCreate<span style="color: #002200;">&#40;</span>kIOPMAssertionTypeNoDisplaySleep, 
                                    kIOPMAssertionLevelOn, <span style="color: #002200;">&amp;</span>assertionID<span style="color: #002200;">&#41;</span>; 
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>success <span style="color: #002200;">==</span> kIOReturnSuccess<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
&nbsp;
    <span style="color: #11740a; font-style: italic;">//Add the work you need to do without </span>
    <span style="color: #11740a; font-style: italic;">//  the system sleeping here.</span>
&nbsp;
    success <span style="color: #002200;">=</span> IOPMAssertionRelease<span style="color: #002200;">&#40;</span>assertionID<span style="color: #002200;">&#41;</span>;
    <span style="color: #11740a; font-style: italic;">//The system will be able to sleep again. </span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


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

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

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

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

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

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

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

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

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

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


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


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

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

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

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

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

<p><a href='http://www.cimgf.com/wp-content/uploads/2009/01/log.zip'>Logging Sample Application</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2009/01/24/dropping-nslog-in-release-builds/feed/</wfw:commentRss>
		<slash:comments>11</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[Objective-C]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></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>4</slash:comments>
		</item>
		<item>
		<title>Core Animation Tutorial: Interrupting Animation Progress</title>
		<link>http://www.cimgf.com/2008/11/05/core-animation-tutorial-interrupting-animation-progress/</link>
		<comments>http://www.cimgf.com/2008/11/05/core-animation-tutorial-interrupting-animation-progress/#comments</comments>
		<pubDate>Thu, 06 Nov 2008 00:10:46 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[Objective-C]]></category>

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

<h2>Differentiating Keypath From Key</h2>

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


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


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

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

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

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

<p>By setting a delegate for the animation, we can be notified when animation has been removed from the animations dictionary. We implement the <em>-animationDidStop:finished</em> delegate.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>animationDidStop<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CAAnimation <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>theAnimation finished<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>flag
<span style="color: #002200;">&#123;</span>
    NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Animation interrupted: %@&quot;</span>, <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>flag<span style="color: #002200;">&#41;</span>?<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Yes&quot;</span> <span style="color: #002200;">:</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;No&quot;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


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

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

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

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

<p>Look no further than the <em>presentationLayer</em> which is accessible through our layer object. We can obtain the last location of our &#8220;position&#8221; parameter by first getting the presentationLayer and getting the position from it instead. We&#8217;ve modified our <em>-mouseDown</em> event to reflect this change.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>mouseDown<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSEvent</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>event;
<span style="color: #002200;">&#123;</span>
  CABasicAnimation <span style="color: #002200;">*</span>animation <span style="color: #002200;">=</span> 
          <span style="color: #002200;">&#91;</span>CABasicAnimation animationWithKeyPath<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;position&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>animation setDelegate<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #11740a; font-style: italic;">// Get the presentationLayer</span>
  CALayer <span style="color: #002200;">*</span>p <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>CALayer<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span>objectLayer presentationLayer<span style="color: #002200;">&#93;</span>;
  CGPoint position <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>p position<span style="color: #002200;">&#93;</span>;
  <span style="color: #400080;">NSValue</span> <span style="color: #002200;">*</span>prevVal <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSValue</span> valueWithPoint<span style="color: #002200;">:</span>
                      NSPointFromCGPoint<span style="color: #002200;">&#40;</span>position<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>animation setFromValue<span style="color: #002200;">:</span>prevVal<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>animation setToValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSValue</span> valueWithPoint<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>event locationInWindow<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>animation setDuration<span style="color: #002200;">:</span><span style="color: #2400d9;">2.0</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>animation setRemovedOnCompletion<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>objectLayer addAnimation<span style="color: #002200;">:</span>animation forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;follow&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


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

<h2>Conclusion</h2>

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

<p><a href='http://www.cimgf.com/wp-content/uploads/2008/11/followme.zip'><img src="http://www.cimgf.com/wp-content/uploads/2008/03/xcode.png" alt="xcode.png" border="0" width="64"/><br />Follow Me Demo Project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/11/05/core-animation-tutorial-interrupting-animation-progress/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Announcement: Marcus&#8217; Core Data Book Just Went Beta!</title>
		<link>http://www.cimgf.com/2008/10/27/announcement-marcus-core-data-book-just-went-beta/</link>
		<comments>http://www.cimgf.com/2008/10/27/announcement-marcus-core-data-book-just-went-beta/#comments</comments>
		<pubDate>Mon, 27 Oct 2008 18:23:12 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Announcement]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[News]]></category>

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

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

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

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

<p>Mad props to Marcus. Congratulations!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/10/27/announcement-marcus-core-data-book-just-went-beta/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Core Animation Tutorial: Slider Based Layer Rotation</title>
		<link>http://www.cimgf.com/2008/10/25/core-animation-tutorial-slider-based-layer-rotation/</link>
		<comments>http://www.cimgf.com/2008/10/25/core-animation-tutorial-slider-based-layer-rotation/#comments</comments>
		<pubDate>Sun, 26 Oct 2008 00:15:50 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[Objective-C]]></category>

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

<h2>The Slider Value</h2>

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

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

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

<h2>Rotation Animation</h2>

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


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


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


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>sliderChange<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender;
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>degreesTextLayer setString<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%f&quot;</span>, <span style="color: #002200;">&#91;</span>slider floatValue<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>needleLayer addAnimation<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self rotateAnimation<span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;rotate&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>needleLayer setNeedsDisplay<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>You will notice that we call -setNeedsDisplay on the layer. This is necessary as we have implemented the delegate method -drawLayer:inContext. We use this method to draw the vertical and horizontal black lines that intersect in the center of the circle layer.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>drawLayer<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CALayer <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>layer inContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGContextRef<span style="color: #002200;">&#41;</span>context;
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span> layer <span style="color: #002200;">==</span> needleLayer <span style="color: #002200;">&#41;</span>
  <span style="color: #002200;">&#123;</span>
      CGMutablePathRef path <span style="color: #002200;">=</span> CGPathCreateMutable<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
      CGPathMoveToPoint<span style="color: #002200;">&#40;</span>path,<span style="color: #a61390;">NULL</span>, <span style="color: #002200;">&#91;</span>view bounds<span style="color: #002200;">&#93;</span>.size.width<span style="color: #002200;">/</span><span style="color: #2400d9;">2.0</span>, <span style="color: #2400d9;">0.0</span><span style="color: #002200;">&#41;</span>;
      CGPathAddLineToPoint<span style="color: #002200;">&#40;</span>path, <span style="color: #a61390;">NULL</span>, <span style="color: #002200;">&#91;</span>view bounds<span style="color: #002200;">&#93;</span>.size.width<span style="color: #002200;">/</span><span style="color: #2400d9;">2.0</span>, <span style="color: #002200;">&#91;</span>view bounds<span style="color: #002200;">&#93;</span>.size.height<span style="color: #002200;">&#41;</span>;
&nbsp;
      CGPathMoveToPoint<span style="color: #002200;">&#40;</span>path,<span style="color: #a61390;">NULL</span>, <span style="color: #2400d9;">0.0</span>, <span style="color: #002200;">&#91;</span>view bounds<span style="color: #002200;">&#93;</span>.size.height<span style="color: #002200;">/</span><span style="color: #2400d9;">2.0</span><span style="color: #002200;">&#41;</span>;
      CGPathAddLineToPoint<span style="color: #002200;">&#40;</span>path, <span style="color: #a61390;">NULL</span>, <span style="color: #002200;">&#91;</span>view bounds<span style="color: #002200;">&#93;</span>.size.width, <span style="color: #002200;">&#91;</span>view bounds<span style="color: #002200;">&#93;</span>.size.height<span style="color: #002200;">/</span><span style="color: #2400d9;">2.0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
      CGColorRef black <span style="color: #002200;">=</span>
              CGColorCreateGenericRGB<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0.0</span>, <span style="color: #2400d9;">0.0</span>, <span style="color: #2400d9;">0.0</span>, <span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#41;</span>;
      CGContextSetStrokeColorWithColor<span style="color: #002200;">&#40;</span>context, black<span style="color: #002200;">&#41;</span>;
      CFRelease<span style="color: #002200;">&#40;</span>black<span style="color: #002200;">&#41;</span>;
&nbsp;
      CGContextBeginPath<span style="color: #002200;">&#40;</span>context<span style="color: #002200;">&#41;</span>;
      CGContextAddPath<span style="color: #002200;">&#40;</span>context, path<span style="color: #002200;">&#41;</span>;
&nbsp;
      CGContextSetLineWidth<span style="color: #002200;">&#40;</span>context, <span style="color: #2400d9;">3.0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
      CGContextStrokePath<span style="color: #002200;">&#40;</span>context<span style="color: #002200;">&#41;</span>;
&nbsp;
      CFRelease<span style="color: #002200;">&#40;</span>path<span style="color: #002200;">&#41;</span>;
&nbsp;
  <span style="color: #002200;">&#125;</span>  
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<h2>Retaining The Rotation Position</h2>

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


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


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

<h2>Conclusion</h2>

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

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

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


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


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

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

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

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

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


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


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

<h2>Your Own Composition</h2>

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

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

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

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

<p>You can see I added a CATextLayer to the QCCompositionLayer which displays the words, &#8220;hello World&#8221;. I also applied a Gaussian blur filter to the whole thing so you can see how easy it is to add filters as well. Here is <em>all</em> of the code needed to make this work.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>awakeFromNib;
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>window contentView<span style="color: #002200;">&#93;</span> setWantsLayer<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>path <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSBundle</span> mainBundle<span style="color: #002200;">&#93;</span> 
                      pathForResource<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;VideoCube&quot;</span> 
                      ofType<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;qtz&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    QCCompositionLayer <span style="color: #002200;">*</span>layer <span style="color: #002200;">=</span> 
        <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>QCCompositionLayer alloc<span style="color: #002200;">&#93;</span> initWithFile<span style="color: #002200;">:</span>path<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span>layer setFrame<span style="color: #002200;">:</span>NSRectToCGRect<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>window contentView<span style="color: #002200;">&#93;</span> frame<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    CATextLayer <span style="color: #002200;">*</span>text <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CATextLayer layer<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>text setString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;hello World&quot;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>text setFrame<span style="color: #002200;">:</span>NSRectToCGRect<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>window contentView<span style="color: #002200;">&#93;</span> frame<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>layer addSublayer<span style="color: #002200;">:</span>text<span style="color: #002200;">&#93;</span>;
&nbsp;
    CIFilter <span style="color: #002200;">*</span>blurFilter <span style="color: #002200;">=</span> 
    <span style="color: #002200;">&#91;</span>CIFilter filterWithName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;CIGaussianBlur&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span>blurFilter setDefaults<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>blurFilter setValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithFloat<span style="color: #002200;">:</span><span style="color: #2400d9;">2.0</span><span style="color: #002200;">&#93;</span> 
                  forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;inputRadius&quot;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>blurFilter setName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;blur&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span>layer setFilters<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSArray</span> arrayWithObject<span style="color: #002200;">:</span>blurFilter<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
&nbsp;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>window contentView<span style="color: #002200;">&#93;</span> layer<span style="color: #002200;">&#93;</span> addSublayer<span style="color: #002200;">:</span>layer<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


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

<h2>Conclusion</h2>

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

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

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

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

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

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

<h3>Scriptable plug-ins</h3>

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

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

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

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

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

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

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

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


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


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


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


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

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

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

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

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

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

</a>
</div>

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

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

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

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

</a>
</div>

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

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

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

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

</a>
</div>

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

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

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

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

</a>
</div>

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


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


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

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

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

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

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

</a>
</div>

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

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

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

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

</a>
</div>

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

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

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

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

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

<p>And the code for this is as follows:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSArray</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>loadPlugins
<span style="color: #002200;">&#123;</span>
  <span style="color: #400080;">NSBundle</span> <span style="color: #002200;">*</span>main <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSBundle</span> mainBundle<span style="color: #002200;">&#93;</span>;
  <span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>all <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>main pathsForResourcesOfType<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;bundle&quot;</span> 
                                   inDirectory<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;../PlugIns&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #400080;">NSMutableArray</span> <span style="color: #002200;">*</span>availablePlugins <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableArray</span> array<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #a61390;">id</span> plugin <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
  <span style="color: #400080;">NSBundle</span> <span style="color: #002200;">*</span>pluginBundle <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
  <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>path <span style="color: #a61390;">in</span> all<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    pluginBundle <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSBundle</span> bundleWithPath<span style="color: #002200;">:</span>path<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>pluginBundle load<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">Class</span> prinClass <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>pluginBundle principalClass<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>prinClass isSubclassOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>AbstractPlugin class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      <span style="color: #a61390;">continue</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    plugin <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>prinClass alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>availablePlugins addObject<span style="color: #002200;">:</span>plugin<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>plugin release<span style="color: #002200;">&#93;</span>, plugin <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
    pluginBundle <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #a61390;">return</span> availablePlugins;
<span style="color: #002200;">&#125;</span></pre></div></div>


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

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

<p>We really want to call this method before the application has finished loading, therefore we need to add an -init method to our AppDelegate and load the plug-ins there.  This will guarantee that they are loaded before the UI with some obvious benefits.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>init
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>super init<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #a61390;">return</span> <span style="color: #a61390;">nil</span>;
&nbsp;
  <span style="color: #002200;">&#91;</span>self setPlugins<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self loadPlugins<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span></pre></div></div>


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

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

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

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

</a>
</div>

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

<h2>Conclusion</h2>

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

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

<p><center><a href="http://www.cimgf.com/wp-content/uploads/2008/09/frameworks.zip" title="Example Project"><img src="http://www.cimgf.com/wp-content/uploads/2008/03/xcode.png" alt="xcode.png" border="0" width="64"/><br/>Example Project</a></center></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/09/17/cocoa-tutorial-adding-plugins-to-a-cocoa-application/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Core Animation Tutorial: Rendering QuickTime Movies In A CAOpenGLLayer</title>
		<link>http://www.cimgf.com/2008/09/10/core-animation-tutorial-rendering-quicktime-movies-in-a-caopengllayer/</link>
		<comments>http://www.cimgf.com/2008/09/10/core-animation-tutorial-rendering-quicktime-movies-in-a-caopengllayer/#comments</comments>
		<pubDate>Wed, 10 Sep 2008 15:20:38 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[Core Video]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[QTKit]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=219</guid>
		<description><![CDATA[I&#8217;ve been experimenting a great deal lately with OpenGL and QuickTime trying to see how the two technologies work together. It&#8217;s been a bit challenging, but fortunately Apple provides two really great resources&#8211;number one, sample code. I&#8217;ve been able to learn a lot just from the samples they provide in the development tools examples as [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been experimenting a great deal lately with OpenGL and QuickTime trying to see how the two technologies work together. It&#8217;s been a bit challenging, but fortunately Apple provides two really great resources&#8211;number one, sample code. I&#8217;ve been able to learn a lot just from the samples they provide in the development tools examples as well as online. And second, the cocoa-dev and quicktime-api lists are great. Lot&#8217;s of brilliant people there who are willing to share their knowledge. It&#8217;s very helpful, prohibition to discuss the iPhone SDK notwithstanding.</p>

<p>Getting two technologies to work together can be a challenge especially when the bridges between the two are not necessarily clearly laid out in documentation. As I pointed out Apple provides some excellent sample code to help you along, but there is no hand-holding approach to any of it. I actually appreciate that having come from the Windows world as it seems that there all you get sometimes is hand-holding where Microsoft doesn&#8217;t trust you, the developer to figure things out and really own what you&#8217;re doing. But I digress (wouldn&#8217;t be a CIMGF post if I didn&#8217;t dig on MS a bit).
<span id="more-219"></span></p>

<p>Like peanut butter and chocolate, what you get when you put together QuickTime and OpenGL is something greater than either of them left on their own (ok, this is subjective. Not everyone likes peanut butter and chocolate together, but again, I digress).</p>

<p>If you read the <a href="http://developer.apple.com/documentation/GraphicsImaging/Conceptual/CoreVideo/CVProg_Intro/chapter_1_section_1.html">Core Video Programming Guide</a> from Apple, you see they provide the reasons for using Core Video:</p>

<blockquote>
CoreVideo is necessary only if you want to manipulate individual video frames. For example, the following types of video processing would require CoreVideo:
<ul>
<li>Color correction or other filtering, such as provided by Core Image filters 
<li>Physical transforms of the video images (such as warping, or mapping on to a surface) 
<li>Adding video to an OpenGL scene 
<li>Adding additional information to frames, such as a visible timecode 
<li>Compositing multiple video streams 
</ul>
</blockquote>

<p>If all you need to do is display a movie, you should simply use either a QTMovieView or, if you want to stick with the Core Animation route, use a QTMovieLayer. They both function similarly, however, the view provides a lot of features that you won&#8217;t have to implement in the UI yourself such as a scrubber or play/pause buttons. Plus the view is very fast and efficient. I&#8217;m in the process of exploring performance differences between the two, but I will save my comments about that for another post.</p>

<p>For our example code we are most interested in the third point above&#8211;<strong>adding video to an OpenGL scene</strong>. It seems that new QuickTime developers often want to know how to manipulate movie images before displaying them. Often this leads them to pursue adding sub-views to the movie view which can become a big mess. Because we are using OpenGL, doing other drawing on the scene is very fast. I won&#8217;t kid you. OpenGL is a pain. I don&#8217;t know anybody who loves it, but everybody respects it because of its raw speed.</p>

<p>Point number five above&#8211;<strong>compositing multiple video streams</strong>&#8211;is also interesting. While I won&#8217;t be covering it in this post, I will say that it makes a world of difference performance wise if you composite the movies into a OpenGL scene. If you&#8217;ve ever tried to run multiple videos simultaneously in two different views or layers, it can get pretty herky jerky. You can see why it is necessary to use OpenGL instead.</p>

<h2>The OpenGL QuickTime Two Step</h2>

<p>Ok, it actually will take more than two steps, however, when you are working with Core Animation layers things get a whole lot easier than they are for rendering a movie in an NSOpenGLView. Here is what you get for free, as the kids say.</p>

<ul>
<li>You don&#8217;t have to set up the OpenGL context. It is already available for you to send your OpenGL calls to.
<li>The viewport for display is already configured
<li>You don&#8217;t need to set up a display link callback
</ul>

<p>What took over 400 lines of code when rendering a QuickTime movie with no filters to an NSOpengGLView now only takes around 150 lines. Any time you can reduce code to something simpler, it makes life easier. It also makes it much easier to grok, in my opinion.</p>

<p>There really are two primary steps you take when using a CAOpenGLLayer. First you check to see if you should draw. Then, depending upon the answer, drawInCGLContext gets called or doesn&#8217;t. Really thats it. Determining whether or not you should draw depends upon what you are trying to do. In our case, we only want to draw if all of the following are true:</p>

<ul>
<li>The movie is actually playing back
<li>The visual context for the movie has been initialized
<li>The visual context has a new image ready to be rendered
</ul>

<p>If all of these are true, then our call to canDrawInCGLContext returns YES. Here is the code I use to check these contraints in canDrawInCGLContext:</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
</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>canDrawInCGLContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGLContextObj<span style="color: #002200;">&#41;</span>glContext 
                pixelFormat<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGLPixelFormatObj<span style="color: #002200;">&#41;</span>pixelFormat 
               forLayerTime<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CFTimeInterval<span style="color: #002200;">&#41;</span>timeInterval 
                displayTime<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">const</span> CVTimeStamp <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>timeStamp
<span style="color: #002200;">&#123;</span> 
    <span style="color: #11740a; font-style: italic;">// There is no point in trying to draw anything if our</span>
    <span style="color: #11740a; font-style: italic;">// movie is not playing.</span>
    <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span> <span style="color: #002200;">&#91;</span>movie rate<span style="color: #002200;">&#93;</span> &lt;<span style="color: #002200;">=</span> <span style="color: #2400d9;">0.0</span> <span style="color: #002200;">&#41;</span>
        <span style="color: #a61390;">return</span> <span style="color: #a61390;">NO</span>;
&nbsp;
    <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span> <span style="color: #002200;">!</span>qtVisualContext <span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        <span style="color: #11740a; font-style: italic;">// If our visual context for our QTMovie has not been set up</span>
        <span style="color: #11740a; font-style: italic;">// we initialize it now</span>
        <span style="color: #002200;">&#91;</span>self setupVisualContext<span style="color: #002200;">:</span>glContext withPixelFormat<span style="color: #002200;">:</span>pixelFormat<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #11740a; font-style: italic;">// Check to see if a new frame (image) is ready to be draw at</span>
    <span style="color: #11740a; font-style: italic;">// the time specified.</span>
    <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span>QTVisualContextIsNewImageAvailable<span style="color: #002200;">&#40;</span>qtVisualContext,timeStamp<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        <span style="color: #11740a; font-style: italic;">// Release the previous frame</span>
        CVOpenGLTextureRelease<span style="color: #002200;">&#40;</span>currentFrame<span style="color: #002200;">&#41;</span>;
&nbsp;
        <span style="color: #11740a; font-style: italic;">// Copy the current frame into our image buffer</span>
        QTVisualContextCopyImageForTime<span style="color: #002200;">&#40;</span>qtVisualContext,
                                        <span style="color: #a61390;">NULL</span>,
                                        timeStamp,
                                        <span style="color: #002200;">&amp;</span>currentFrame<span style="color: #002200;">&#41;</span>;
&nbsp;
        <span style="color: #11740a; font-style: italic;">// Returns the texture coordinates for the part of the image that should be displayed</span>
        CVOpenGLTextureGetCleanTexCoords<span style="color: #002200;">&#40;</span>
                            currentFrame, 
                            lowerLeft, 
                            lowerRight, 
                            upperRight, upperLeft<span style="color: #002200;">&#41;</span>;
        <span style="color: #a61390;">return</span> <span style="color: #a61390;">YES</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #a61390;">return</span> <span style="color: #a61390;">NO</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>The call to setup the visual context is where we are associating the QuickTime movie itself with a QTVisualContextRef object which is what OpenGL needs to draw the current frame. We will then use this object to load image data into a CVImageBufferRef which can be used for rendering with OpenGL. Here is the code to set up the visual context.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setupVisualContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGLContextObj<span style="color: #002200;">&#41;</span>glContext 
           withPixelFormat<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGLPixelFormatObj<span style="color: #002200;">&#41;</span>pixelFormat;
<span style="color: #002200;">&#123;</span>
    OSStatus			    error;
&nbsp;
    <span style="color: #400080;">NSDictionary</span>	    <span style="color: #002200;">*</span>attributes <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
    attributes <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSDictionary</span> dictionaryWithObjectsAndKeys<span style="color: #002200;">:</span>
                  <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSDictionary</span> dictionaryWithObjectsAndKeys<span style="color: #002200;">:</span>
                   <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithFloat<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self frame<span style="color: #002200;">&#93;</span>.size.width<span style="color: #002200;">&#93;</span>,
                   kQTVisualContextTargetDimensions_WidthKey,
                   <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithFloat<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self frame<span style="color: #002200;">&#93;</span>.size.height<span style="color: #002200;">&#93;</span>,
                   kQTVisualContextTargetDimensions_HeightKey, <span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>, 
                  kQTVisualContextTargetDimensionsKey, 
                  <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSDictionary</span> dictionaryWithObjectsAndKeys<span style="color: #002200;">:</span>
                   <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithFloat<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self frame<span style="color: #002200;">&#93;</span>.size.width<span style="color: #002200;">&#93;</span>, 
                   kCVPixelBufferWidthKey, 
                   <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithFloat<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self frame<span style="color: #002200;">&#93;</span>.size.height<span style="color: #002200;">&#93;</span>, 
                   kCVPixelBufferHeightKey, <span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>, 
                  kQTVisualContextPixelBufferAttributesKey,
                  <span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// Create our quicktimee visual context</span>
    error <span style="color: #002200;">=</span> QTOpenGLTextureContextCreate<span style="color: #002200;">&#40;</span><span style="color: #a61390;">NULL</span>,
                                         glContext,
                                         pixelFormat,
                                         <span style="color: #002200;">&#40;</span>CFDictionaryRef<span style="color: #002200;">&#41;</span>attributes,
                                         <span style="color: #002200;">&amp;</span>qtVisualContext<span style="color: #002200;">&#41;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// Associate it with our movie.</span>
    SetMovieVisualContext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>movie quickTimeMovie<span style="color: #002200;">&#93;</span>,qtVisualContext<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>Next we check to see if there is an image ready using:</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;"><span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span>QTVisualContextIsNewImageAvailable<span style="color: #002200;">&#40;</span>qtVisualContext,timeStamp<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span></pre></td></tr></table></div>


<p>And then we copy the image to our CVImageBufferRef with:</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;">// Copy the current frame into our image buffer</span>
QTVisualContextCopyImageForTime<span style="color: #002200;">&#40;</span>qtVisualContext,
                                <span style="color: #a61390;">NULL</span>,
                                timeStamp,
                                <span style="color: #002200;">&amp;</span>currentFrame<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>


<p>Now it&#8217;s all a matter of rendering the frame for the current time stamp.</p>

<h2>But Wait! What TimeStamp?</h2>

<p>If you asked this question, then you are a very astute reader. In order to obtain the next image, we simply passed the CVTimeStamp parameter, <em>timeStamp</em> to our call to QTVisualContextCopyImageForTime. But how do we even have a timestamp? Isn&#8217;t that something we need to get from a display link? If you&#8217;re asking what is a display link at this point, take a look at the <a href="http://developer.apple.com/documentation/GraphicsImaging/Conceptual/CoreVideo/CVProg_Concepts/chapter_2_section_3.html">Core Video Programming Guide</a> which states:</p>

<blockquote>
To simplify synchronization of video with a displayâ€™s refresh rate, Core Video provides a special timer called a display link. The display link runs as a separate high priority thread, which is not affected by interactions within your application process.

In the past, synchronizing your video frames with the displayâ€™s refresh rate was often a problem, especially if you also had audio. You could only make simple guesses for when to output a frame (by using a timer, for example), which didnâ€™t take into account possible latency from user interactions, CPU loading, window compositing and so on. The Core Video display link can make intelligent estimates for when a frame needs to be output, based on display type and latencies.
</blockquote>

<p>I will provide a more complete answer to the question in the future as I am still studying it myself, however, I will mention that a display link callback is unnecessary in this context as the CAOpenGLLayer is providing this for us. The timestamp field is all we need in order to get the current frame assuming that the movie is playing back.</p>

<h2>Drawing The Frame</h2>

<p>There is a special group of people who really get OpenGL. I salute all of you to whom this applies. You are amazing. I, however, only write as much of it as necessary and you&#8217;ll see that most of the code I have here is simply a copy and paste from sample code I got from Apple. I am starting to understand it more and more, however, it makes my brain hurt. Here is my drawing code for when a frame is ready to be rendered.</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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
</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>drawInCGLContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGLContextObj<span style="color: #002200;">&#41;</span>glContext 
             pixelFormat<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGLPixelFormatObj<span style="color: #002200;">&#41;</span>pixelFormat 
            forLayerTime<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CFTimeInterval<span style="color: #002200;">&#41;</span>interval 
             displayTime<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">const</span> CVTimeStamp <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>timeStamp
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">NSRect</span>    bounds <span style="color: #002200;">=</span> NSRectFromCGRect<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>self bounds<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
    GLfloat 	minX, minY, maxX, maxY;        
&nbsp;
    minX <span style="color: #002200;">=</span> NSMinX<span style="color: #002200;">&#40;</span>bounds<span style="color: #002200;">&#41;</span>;
    minY <span style="color: #002200;">=</span> NSMinY<span style="color: #002200;">&#40;</span>bounds<span style="color: #002200;">&#41;</span>;
    maxX <span style="color: #002200;">=</span> NSMaxX<span style="color: #002200;">&#40;</span>bounds<span style="color: #002200;">&#41;</span>;
    maxY <span style="color: #002200;">=</span> NSMaxY<span style="color: #002200;">&#40;</span>bounds<span style="color: #002200;">&#41;</span>;
&nbsp;
    glMatrixMode<span style="color: #002200;">&#40;</span>GL_MODELVIEW<span style="color: #002200;">&#41;</span>;
    glLoadIdentity<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
    glMatrixMode<span style="color: #002200;">&#40;</span>GL_PROJECTION<span style="color: #002200;">&#41;</span>;
    glLoadIdentity<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
    glOrtho<span style="color: #002200;">&#40;</span> minX, maxX, minY, maxY, <span style="color: #002200;">-</span><span style="color: #2400d9;">1.0</span>, <span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
    glClearColor<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0.0</span>, <span style="color: #2400d9;">0.0</span>, <span style="color: #2400d9;">0.0</span>, <span style="color: #2400d9;">0.0</span><span style="color: #002200;">&#41;</span>;	     
    glClear<span style="color: #002200;">&#40;</span>GL_COLOR_BUFFER_BIT<span style="color: #002200;">&#41;</span>;
&nbsp;
    CGRect imageRect <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self frame<span style="color: #002200;">&#93;</span>;
    <span style="color: #11740a; font-style: italic;">// Enable target for the current frame</span>
    glEnable<span style="color: #002200;">&#40;</span>CVOpenGLTextureGetTarget<span style="color: #002200;">&#40;</span>currentFrame<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #11740a; font-style: italic;">// Bind to the current frame</span>
    <span style="color: #11740a; font-style: italic;">// This tells OpenGL which texture we are wanting </span>
    <span style="color: #11740a; font-style: italic;">// to draw so that when we make our glTexCord and </span>
    <span style="color: #11740a; font-style: italic;">// glVertex calls, our current frame gets drawn</span>
    <span style="color: #11740a; font-style: italic;">// to the context.</span>
    glBindTexture<span style="color: #002200;">&#40;</span>CVOpenGLTextureGetTarget<span style="color: #002200;">&#40;</span>currentFrame<span style="color: #002200;">&#41;</span>, 
                  CVOpenGLTextureGetName<span style="color: #002200;">&#40;</span>currentFrame<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
    glMatrixMode<span style="color: #002200;">&#40;</span>GL_TEXTURE<span style="color: #002200;">&#41;</span>;
    glLoadIdentity<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
    glColor4f<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1.0</span>, <span style="color: #2400d9;">1.0</span>, <span style="color: #2400d9;">1.0</span>, <span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#41;</span>;
    glBegin<span style="color: #002200;">&#40;</span>GL_QUADS<span style="color: #002200;">&#41;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// Draw the quads</span>
    glTexCoord2f<span style="color: #002200;">&#40;</span>upperLeft<span style="color: #002200;">&#91;</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>, upperLeft<span style="color: #002200;">&#91;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
    glVertex2f  <span style="color: #002200;">&#40;</span>imageRect.origin.x, 
                 imageRect.origin.y <span style="color: #002200;">+</span> imageRect.size.height<span style="color: #002200;">&#41;</span>;
    glTexCoord2f<span style="color: #002200;">&#40;</span>upperRight<span style="color: #002200;">&#91;</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>, upperRight<span style="color: #002200;">&#91;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
    glVertex2f  <span style="color: #002200;">&#40;</span>imageRect.origin.x <span style="color: #002200;">+</span> imageRect.size.width, 
                 imageRect.origin.y <span style="color: #002200;">+</span> imageRect.size.height<span style="color: #002200;">&#41;</span>;
    glTexCoord2f<span style="color: #002200;">&#40;</span>lowerRight<span style="color: #002200;">&#91;</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>, lowerRight<span style="color: #002200;">&#91;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
    glVertex2f  <span style="color: #002200;">&#40;</span>imageRect.origin.x <span style="color: #002200;">+</span> imageRect.size.width, 
                 imageRect.origin.y<span style="color: #002200;">&#41;</span>;
    glTexCoord2f<span style="color: #002200;">&#40;</span>lowerLeft<span style="color: #002200;">&#91;</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>, lowerLeft<span style="color: #002200;">&#91;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
    glVertex2f  <span style="color: #002200;">&#40;</span>imageRect.origin.x, imageRect.origin.y<span style="color: #002200;">&#41;</span>;
&nbsp;
    glEnd<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// This CAOpenGLLayer is responsible to flush</span>
    <span style="color: #11740a; font-style: italic;">// the OpenGL context so we call super</span>
    <span style="color: #002200;">&#91;</span>super drawInCGLContext<span style="color: #002200;">:</span>glContext 
                pixelFormat<span style="color: #002200;">:</span>pixelFormat 
               forLayerTime<span style="color: #002200;">:</span>interval 
                displayTime<span style="color: #002200;">:</span>timeStamp<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// Task the context</span>
    QTVisualContextTask<span style="color: #002200;">&#40;</span>qtVisualContext<span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>If you&#8217;re not familiar with OpenGL it would help you to know that it&#8217;s all about the current state. What does this mean? Well, simply put, it means that the call you are making right now, applies to whatever state the context is in. These two calls are what are the most important for our purposes.</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;">glEnable<span style="color: #002200;">&#40;</span>CVOpenGLTextureGetTarget<span style="color: #002200;">&#40;</span>currentFrame<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
glBindTexture<span style="color: #002200;">&#40;</span>CVOpenGLTextureGetTarget<span style="color: #002200;">&#40;</span>currentFrame<span style="color: #002200;">&#41;</span>, 
                  CVOpenGLTextureGetName<span style="color: #002200;">&#40;</span>currentFrame<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>


<p>With these two calls we have told OpenGL which texture to use. Now, every subsequent call applies to this texture until the state is changed to something else. So now, when we set a color or draw a quad, it applies to the texture that has been set here.</p>

<h2>Conclusion</h2>

<p>I love both of these technologies, QuickTime and OpenGL. They are so powerful. It&#8217;s harnessing the power that&#8217;s the trick. I&#8217;ve got some other ideas for some related posts that I plan to cover in the weeks to come, but this was a real breakthrough for me. With the help of John Clayton, Jean-Daniel Dupas, and David Duncan on the cocoa-dev list, I was able to get the sample code put together for this post. Feel free to ask questions in the comments. I will do my best to answer, but I&#8217;m still pretty new to these technologies. Write some code yourself and have fun. This is really exciting stuff. Until next time.</p>

<h2>About The Demo Code</h2>

<p><strike>John Clayton has some issues getting the code to work on his Mac Pro. I successfully ran it on  my MacBook Pro, and the family iMac without any issues. Anyhow, we&#8217;re not sure what the problem is, so if you do run into trouble, let me know. Maybe we can figure it out. Meanwhile we&#8217;re investigating it as we have time.</strike></p>

<p><strong>Update:</strong> John Clayton figured it out. Apparently the visual context needs to be reset because the pixel format is not correct on the first run. We just reset the visual context now in the call to -copyCGLContextForPixelFormat and everything seems happy. The demo code has been updated to reflect the change.</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2008/09/qtglcalayerdemo.zip'><img src="http://www.cimgf.com/wp-content/uploads/2008/03/xcode.png" alt="Quicktime CAOpenGLLayer Demo" title="Quicktime CAOpenGLLayer Demo" width="64" class="aligncenter size-medium wp-image-49" /><br />Quicktime CAOpenGLLayer Demo</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/09/10/core-animation-tutorial-rendering-quicktime-movies-in-a-caopengllayer/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Cocoa Tutorial: Creating your very own framework</title>
		<link>http://www.cimgf.com/2008/09/04/cocoa-tutorial-creating-your-very-own-framework/</link>
		<comments>http://www.cimgf.com/2008/09/04/cocoa-tutorial-creating-your-very-own-framework/#comments</comments>
		<pubDate>Thu, 04 Sep 2008 18:05:25 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=229</guid>
		<description><![CDATA[There are numerous situations where creating your own framework is advantageous. Perhaps you have a block of code that you use repeatedly in many different projects. Perhaps you are building a plug-in system for your application and want the infrastructure to be available both to the application and to any plugins that are coded. A [...]]]></description>
			<content:encoded><![CDATA[<p>There are numerous situations where creating your own framework is advantageous.  Perhaps you have a block of code that you use repeatedly in many different projects.  Perhaps you are building a plug-in system for your application and want the infrastructure to be available both to the application and to any plugins that are coded.</p>

<p>A Cocoa framework is another project type in Xcode.  The end result is a bundle, similar to an application bundle.  Inside of this bundle is the compiled code you wrote and any headers that you want exposed.  The headers are important.  Without them, just like any other piece of Objective-C code, it is very hard to code against.</p>

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

<h2>Building a Framework in Xcode</h2>

<p>Building a framework within Xcode is straight-forward.  There is already a project template specifically for Cocoa frameworks so that is where we will start.</p>

<div style="text-align:center;"> <a href="http://www.cimgf.com/wp-content/uploads/2008/09/newframework.png" rel="lightbox" title="New Framework Project"><img src="http://www.cimgf.com/wp-content/uploads/2008/09/newframework.png" width="250"alt="New Framework Project" /></a></div>

<p>Once the framework is build, the rest of the code development is almost identical to an application bundle.  C, C++ and Objective-C files can be included along with nibs, xibs, images and just about anything else we would stick into an application bundle.  When the code is complied, the end result is also a bundle, again very similar to an application.  The bundle structure, however, is a bit different and will be discussed in detail below.</p>

<p>Care must be given to the headers that we write and that we expose as part of that framework.  In general, we really only want to expose the headers that users of the framework are going to interact with.  If a header is completely internal to the framework then do not plan on exposing it.  In addition, it is a good idea to have a wrapper header that users can import and gain references to all of the public headers.  Since a framework will undoubtably contain more than one class file, how do we roll all of that up into one header?  One solution I have seen is to create a separate header file and copy all of the interfaces into it.  Unfortunately that solution can become unwieldy very quickly.  My preferred solution is to build a &#8220;wrapper&#8221; header file that imports all of the headers that you want exposed.  This is demonstrated in <i>Code Sample 1</i>.</p>

<hr/>

<p><small><strong><i>Code Sample 1: Example.h</i></strong></small></p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;ExampleOne.h&quot;</span>
<span style="color: #6e371a;">#import &quot;ExampleTwo.h&quot;</span></pre></div></div>


<p>Once the framework is built but before we distribute it, there are a few tweaks we need to deal with.  First, we need to declare which headers are public and which are project.  There is also an option for private but honestly I cannot see the logic behind them.  If we flag a header as private it gets included in the resulting framework in a directory called &#8220;PrivateHeaders&#8221;.  However, if we flag a header as &#8220;project&#8221; then it is correctly not included in the framework.  Public headers are naturally included in the framework under the Headers directory.</p>

<h2>Which headers should be included</h2>

<p>&lt;</p>

<p>p>For some headers, the answer to that question is easy.  However, there are some gotchas that need to be planned around.  If an object is referenced in one of the public headers then its header must also be public.  Therefore if we want an object to be private/hidden/internal then we need to make sure there are no public references to it anywhere in any of the exposed headers.  For example, if we had a an internal object called InternalObject and we referenced it in our header, the header for InternalObject would need to be public.  See See <em>Image 2</em>.</p>

<div style="text-align:center;"> <a href="http://www.cimgf.com/wp-content/uploads/2008/09/allpublic.png" rel="lightbox" title="All Public Headers"><img src="http://www.cimgf.com/wp-content/uploads/2008/09/allpublic.png" width="250"alt="All Public Headers"/></a></div>

<p>&lt;</p>

<p>p>However, if the reference is an <em>id</em> instead, we can keep the InternalObject private and its header un-exposed.  See <em>Image 3</em>.</p>

<div style="text-align:center;"> <a href="http://www.cimgf.com/wp-content/uploads/2008/09/projectinternal.png" rel="lightbox" title="Project Level InternalObject"><img src="http://www.cimgf.com/wp-content/uploads/2008/09/projectinternal.png" width="250"alt="Project Level InternalObject"/></a></div>

<p>On thing to note is that in both cases, the AbstractExample is public even though we do not want anyone extending it.  Because both ExampleOne and ExampleTwo are subclasses of AbstractExample its header must therefore be included in the framework.  To make this a little confusing, this is NOT the case if the application and the framework both exist in the same project!  If we look at the included project (called Example), and turn AbstractExample to project, everything will work just fine.  However, if we take that compiled framework and use it in the second included project (called Test), it will fail.  Therefore depending on how we are going to use the framework, superclasses will probably need to be included.</p>

<h2>Using the framework</h2>

<p>Now that we have our framework built, how do we use it? There are three places we can put this framework.  We can make it system accessible, user accessible or application accessible.</p>

<h3>System Accessible</h3>

<p>System accessible frameworks are just like the frameworks that come with OS X.  They can be imported into any application.  For this magic to work, however, they need to be installed in a system level folder; specifically /Library/Frameworks.  Go ahed and look in that directory now.  If your system is anything like mine it is empty.  Why?  Because system level frameworks require root access to be installed and therefore require privilege escalation to get them there.  Generally this is a <strong><emph>BAD IDEA</emp></strong> and there are few frameworks that follow this path.</p>

<h3>User Accessible</h3>

<p>User accessible frameworks are very similar to System accessible frameworks.  However they are stored in a user writable location instead; ~/Library/Frameworks.  Go ahead and look for this directory also.  Chances are the directory itself does not even exist.  This is safer than a system accessible framework and if we have a framework that is going to be used by multiple applications then this might be a logical place for it.  But both user accessible frameworks and system frameworks have the same technical challenge discussed below.</p>

<h3>Application Accessible</h3>

<p>Outside of Apple this is the most common usage of a framework.  It is bundled with the application and only the application can access it.  Both of the other locations for frameworks have one issue; how do you get them there?  The answer?  You include them with the application of course!  However, if you have to include them with the application (and you will need to include them with EVERY application that uses them) then what exactly is the point of putting them somewhere else?  This is one of the main reasons that System and User accessible frameworks really don&#8217;t have a point; again outside of Apple.</p>

<h3>Setting the installation directory</h3>

<p>Since it only really makes sense to have our framework be application accessible, we need to tell it that when we build it.  While this is not important for an application that has the framework included in its build cycle, if we want our application to be used by other applications, it becomes critical.  When an application links to a framework, it needs to know where the final resting place of that framework is going to be.  The default for the framework template is ~/Library/Frameworks.  Clearly this needs to change.</p>

<p>To get a framework to acknowledge that it will be used inside of an application, we have to set the installation directory to a relative path.  That relative path is:</p>

<p><pre>
@executable_path/../Frameworks
</pre></p>

<p>Once we have the installation directory set, it is time to include it in our application.</p>

<h3>Setting up the targets for our application</h3>

<p>Looking in the Example project, there are two targets, one for the framework and one for the application.  Opening the application&#8217;s target we can see that the framework is a dependency of the application.  This will insure that the framework will be built whenever we build the application.  In addition, the framework is also in the &#8220;Link Binary With Libraries&#8221; build phase so that our application can build against it.</p>

<div style="text-align:center;"><img src="http://www.cimgf.com/wp-content/uploads/2008/09/apptargets.png" alt="Application Target Structure" border="0" width="229"/></div>

<p>There are also two new build steps for this application that are directly related to the framework.  First, is a Copy Frameworks phase.  This was added using the Project -> New Build Phase -> New Copy Files Build Phase.  I then renamed it to Copy Frameworks for clarity.  Selecting Show Info on the Copy Frameworks build phase will show that its directory is set to &#8220;Frameworks&#8221;.  This will create a Frameworks directory inside of our application build and copy our framework into it.  This is how we distribute a framework with the application.</p>

<p>&lt;</p>

<p>p>The other additional build phase is called &#8220;Clean Framework Headers&#8221; and is a script build phase.  The purpose behind this phase is to delete all of the header files out of the application bundle once everything is finished.  Why?  Because they are not needed at runtime and there is no point in distributing them.  When we distribute the framework on its own we definitely need to leave them but for the included framework they are just wasted bits.  Therefore the script removes them as the final build phase for the application <em>only</em>.  See <em>Code Sample 2</em>.</p>


<div class="wp_syntax"><div class="code"><pre class="perl" style="font-family:monospace;">echo <span style="color: #ff0000;">&quot;build path ${TARGET_BUILD_DIR}&quot;</span>
cd <span style="color: #0000ff;">$</span><span style="color: #009900;">&#123;</span>TARGET_BUILD_DIR<span style="color: #009900;">&#125;</span><span style="color: #339933;">/</span><span style="color: #0000ff;">$</span><span style="color: #009900;">&#123;</span>FULL_PRODUCT_NAME<span style="color: #009900;">&#125;</span><span style="color: #339933;">/</span>Contents<span style="color: #339933;">/</span>Frameworks 
rm <span style="color: #339933;">-</span>rf <span style="color: #339933;">*/</span>Headers 
rm <span style="color: #339933;">-</span>rf <span style="color: #339933;">*/</span>Versions<span style="color: #339933;">/*/</span>Headers 
rm <span style="color: #339933;">-</span>rf <span style="color: #339933;">*/</span>Versions<span style="color: #339933;">/*/</span>PrivateHeaders 
rm <span style="color: #339933;">-</span>rf <span style="color: #339933;">*/</span>Versions<span style="color: #339933;">/*/</span>Resources<span style="color: #339933;">/*/</span>Contents<span style="color: #339933;">/</span>Headers</pre></div></div>


<h2>Framework Structure</h2>

<p>&lt;</p>

<p>p>For the curious, the internal structure of a framework is similar to an application.  There is a compiled binary and a Resources directory that contains all of the xib, nibs, etc.  There is also a Headers directory (and in some cases a PrivateHeaders directory) that contains all of the exposed header files.  Where things chance is that a framework is versionable.  The actual headers, resources and binary are actually stored in the Versions/${VERSION} subdirectory.  From that directory there are sym-links up to the root directory of the bundle and also to the Versions/Current subdirectory.</p>

<p><pre>
${compiled_binary} -> Versions/Current/Example
Headers -> Versions/Current/Headers
Resources -> Versions/Current/Resources
Versions/A/${compiled_binary}
Versions/A/Headers
Versions/A/Resources
Versions/Current -> A
</pre></p>

<p>The purpose of this is to allow multiple versions of a framework to be stored within one bundle.  However it is unlikely you will ever see more than one version in a bundle.  It is a manual process to combine the versions and each version has to be kept in its own xcode project and merged by hand.  In addition, since it really only makes sense to have frameworks inside of application bundles, it does not make much sense to have multiple versions of the framework.  Nevertheless the functionality is there for those pesky edge cases.</p>

<h2>Conclusion</h2>

<p>Frameworks definitely have their place.  They are very useful when writing a plugin architecture, etc.  However, since they only make sense to include them in an application, unless you are sharing the framework or doing plugins, chances are it is better to just include the source code and be done with it.</p>

<p><center></p>

<table>
<tr>
<td><a href="http://www.cimgf.com/wp-content/uploads/2008/09/example.zip" title="Example Project"><img src="http://www.cimgf.com/wp-content/uploads/2008/03/xcode.png" alt="xcode.png" border="0" width="64"/><br/>Example Project</a></td>
<td><a href="http://www.cimgf.com/wp-content/uploads/2008/09/test.zip" title="Test Project"><img src="http://www.cimgf.com/wp-content/uploads/2008/03/xcode.png" alt="xcode.png" border="0" width="64"/><br/>Test Project</a></td>
</tr>
</table>

<p></center></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/09/04/cocoa-tutorial-creating-your-very-own-framework/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Cocoa Tutorial: Sync Services without Core Data</title>
		<link>http://www.cimgf.com/2008/08/27/cocoa-tutorial-sync-services-without-core-data/</link>
		<comments>http://www.cimgf.com/2008/08/27/cocoa-tutorial-sync-services-without-core-data/#comments</comments>
		<pubDate>Wed, 27 Aug 2008 22:23:23 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=216</guid>
		<description><![CDATA[Sync Services have come a long way in Leopard. Before Leopard it was an extremely complex operation that was almost completely manual. Needless to say, this sucked and it was probably one of the reasons it was shunned by most developers. If you are using Core Data in a Leopard application then Sync Services is [...]]]></description>
			<content:encoded><![CDATA[<p>Sync Services have come a long way in Leopard.  Before Leopard it was an extremely complex operation that was almost completely manual.  Needless to say, this sucked and it was probably one of the reasons it was shunned by most developers.</p>

<p>If you are using Core Data in a Leopard application then Sync Services is so trivial that you should be syncing if it makes sense.  In this article we are going to cover syncing in a non-Core Data situation as that is quite a bit more complex.</p>

<p>If you have read the Sync Services documentation then you know it is complex.  Let me dispel an illusion right away.  It is hard.  It is not poor documentation, syncing is very hard and very few people get it right.  Take a look at Omnifocus to see an example of a company thinking it is easy and losing data.  Therefore if you are expecting this subject to be trivial you will be disappointed.</p>

<p>In this example we will be syncing with the bookmarks schema and displaying them in a simple outline view.  The outline view itself will be editable and those edits can be synced back.  Not terribly useful but provides a very simple example.
<span id="more-216"></span></p>

<h2>Sync Services Setup</h2>

<p>There are a few different ways to implement sync services inside of your application.  You can set up a sync client and handle everything manually just like we did in Tiger but to be honest, unless you need Tiger compatibility, I would not use that approach again.  The option we are going to use in this article is new to Leopard and that will be employing a ISyncDriver.  The driver is basically a default sync client that handle some of the mess for us.  To create the driver, we need to pass it a data source:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">syncDriver <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>ISyncSessionDriver sessionDriverWithDataSource<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span> retain<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>syncDriver setDelegate<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>self setPreferredSyncMode<span style="color: #002200;">:</span>ISyncSessionDriverModeFast<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #a61390;">SEL</span> syncSEL <span style="color: #002200;">=</span> <span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>client<span style="color: #002200;">:</span>willSyncEntityNames<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>syncDriver client<span style="color: #002200;">&#93;</span> setSyncAlertHandler<span style="color: #002200;">:</span>self selector<span style="color: #002200;">:</span>syncSEL<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>syncDriver sync<span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>In our example application, we are going to hold on to a reference to the syncDriver object so that we can request syncs whenever it is appropriate.  To be a data source for the ISyncSessionDriver class, the object needs to implement the protocol ISyncSessionDriverDataSource.  While this protocol has a few optional methods, pretty much all of the methods in the protocol are required.  In the example application for this article, the application&#8217;s delegate is also the data source and the delegate.  I would not recommend this for a production application as it makes the application delegate pretty big; it is sufficient for this example.</p>

<p>Once the syncDriver has been initialized, I want to request a sync immediately on start up.  This makes sure that the application is dealing with fresh data as opposed to something that may have changed while the application was not running<sup>1</sup>.  Just before I call [syncDriver sync] though I do want to flag my object as the handler for sync alerts.  This is a callback method used by the sync engine to tell my application that a sync is occurring on data that I care about and it gives me the opportunity to be apart of that sync.  Once I have set myself up as a receiver for those alerts it is time to perform the first sync.</p>

<p>There are essentially three phases when your application is going to perform a sync.  Two of those phases our application will have a direct involvement with.  The first phase, called the push phase, is where we send our data to the Truth.  The Truth is a database that lives on each Mac and keeps track of all the data that is being synced.  The Truth handles all merging of data and each application can request a copy of data from it.</p>

<h3>Push</h3>

<div style="float: right;width: 19em;margin: 0 0 0 0.2em;padding-left: 0.2em;background: #FFFF00;">
    <strong>Entity Names</strong><br/>
    Entity names are similar to bundle identifiers in that they uniquely name a data object.  In this example we are syncing with the system bookmarks so our two entity names we are dealing with are com.apple.Bookmark and com.apple.Folder.
</div>

<p>In the first phase of a sync, we push our data to the Truth.  Since this example application does not retain any data this will be very quick.  The first part of this push, our application needs to list all of the data objects it knows about for each entity type.  The method that handles this is -recordsForEntityName: moreComing: error:.  This method returns a dictionary of all the data for a specific entity name.</p>

<p>In that NSDictionary, the key is the unique identifier for that record which is provided by the Truth.  The object is another NSDictionary with the properties of the object contained within.  In our example application, this method is implemented as follows:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDictionary</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>recordsForEntityName<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>entityName 
                          moreComing<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>moreComing 
                               error<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSError</span><span style="color: #002200;">**</span><span style="color: #002200;">&#41;</span>outError
<span style="color: #002200;">&#123;</span>
	<span style="color: #400080;">NSMutableDictionary</span> <span style="color: #002200;">*</span>dict <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableDictionary</span> dictionary<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>recordID <span style="color: #a61390;">in</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self recordLookup<span style="color: #002200;">&#93;</span> allKeys<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">id</span> object <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self objectForRecordIdentifier<span style="color: #002200;">:</span>recordID<span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>objectEntityName <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>object class<span style="color: #002200;">&#93;</span> entityName<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>objectEntityName isEqualToString<span style="color: #002200;">:</span>entityName<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      <span style="color: #a61390;">continue</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#91;</span>dict setValue<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>object fullRecord<span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span>recordID<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
&nbsp;
  <span style="color: #002200;">*</span>moreComing <span style="color: #002200;">=</span> <span style="color: #a61390;">NO</span>;
  <span style="color: #a61390;">return</span> dict;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>The more coming flag is used when an application wants to send the data in batches.  If it is set to YES then the method will be called repeatedly with the same entityName until a NO is received.  <strong>NOTE:</strong>This method is normally only called on the first sync.</p>

<p>Once our application had told the Truth about all of the data it knows about, the next part of the push phase is to send any changes that have occurred since the last sync.  This is handled in one of two methods.  If our application can accurately describe each property that has changed then the -changesForEntityName: moreComing: error: method can be used.  If, however, we only know that an object has changed but not which specific properties, then the -changedRecordsForEntityName:moreComing:error: method would be used.  The former method is easier on the sync since it does not need to resolve that information itself.  In our implementation we will be using the latter implementation to make our lives easier.</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;">NSDictionary</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>changedRecordsForEntityName<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>entityName 
                                 moreComing<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>moreComing 
                                      error<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSError</span><span style="color: #002200;">**</span><span style="color: #002200;">&#41;</span>outError
<span style="color: #002200;">&#123;</span>
  <span style="color: #400080;">NSMutableDictionary</span> <span style="color: #002200;">*</span>dict <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableDictionary</span> dictionary<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>key <span style="color: #a61390;">in</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self recordLookup<span style="color: #002200;">&#93;</span> allKeys<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">id</span> object <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self recordLookup<span style="color: #002200;">&#93;</span> objectForKey<span style="color: #002200;">:</span>key<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>object updated<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #a61390;">continue</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>object entityName<span style="color: #002200;">&#93;</span> isEqualToString<span style="color: #002200;">:</span>entityName<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #a61390;">continue</span>;
    <span style="color: #002200;">&#91;</span>dict setObject<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>object fullRecord<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;">return</span> dict;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>Here we are looping through all of our objects (we store them in a NSDictionary as well to make life easier in the demo) and if an object has the right entity name as well as being flagged as updated we send its data back.  Again, we can set the moreComing flag to YES if we need to handle the data in batches.</p>

<h3>Mingle</h3>

<p>Once we have pushed our data and our changes up to the server and all of the other participants of this sync session have done the same, the Truth mingles the data.  It will do its best to merge everything and if it fails it will ask the user to decide which change is the correct one.</p>

<p>Clients have no participation in this phase of the sync session.  Once the mingle is complete the next phase is started automatically by the ISyncSessionDriver.</p>

<h3>Push</h3>

<p>Once the data has been mingled, the Truth will then inform each client of any changes that have taken place.  It is expected that each client will accept these changes and store them in their local data stores.  The method that is called is -applyChange:forEntityName:remappedRecordIdentifier:formattedRecord:error:.  This method will be called for each entity that has changed as a result of the mingle so it needs to be as efficient as possible.</p>

<p>When this method is called, a ISyncChange object is passed in.  This object contains all of the information about the change that needs to be performed.  The first thing that needs to be looked at is what type of change it is.  A change can be a new record, deleting an existing record or updating a record.  Our implementation of this method is as follows:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span>ISyncSessionDriverChangeResult<span style="color: #002200;">&#41;</span>applyChange<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>ISyncChange<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>change 
                                forEntityName<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>entityName 
                     remappedRecordIdentifier<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>outRecordIdentifier 
                              formattedRecord<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>outRecord 
                                        error<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSError</span><span style="color: #002200;">**</span><span style="color: #002200;">&#41;</span>err
<span style="color: #002200;">&#123;</span>
  <span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>errDict <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
  <span style="color: #a61390;">id</span> record <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
  <span style="color: #a61390;">switch</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>change type<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">case</span> ISyncChangeTypeDelete<span style="color: #002200;">:</span>
      <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self recordLookup<span style="color: #002200;">&#93;</span> removeObjectForKey<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>change recordIdentifier<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
      <span style="color: #a61390;">return</span> ISyncSessionDriverChangeAccepted;
    <span style="color: #a61390;">case</span> ISyncChangeTypeAdd<span style="color: #002200;">:</span>
      <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>entityName isEqualToString<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>FolderEntity entityName<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        record <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>FolderEntity alloc<span style="color: #002200;">&#93;</span> init<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>entityName isEqualToString<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>BookmarkEntity entityName<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        record <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>BookmarkEntity alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
      <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
        errDict <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;Unknown type&quot;</span>
                                              forKey<span style="color: #002200;">:</span>NSLocalizedDescriptionKey<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">*</span>err <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSError</span> errorWithDomain<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;CIMGF&quot;</span> code<span style="color: #002200;">:</span><span style="color: #2400d9;">8002</span> userInfo<span style="color: #002200;">:</span>errDict<span style="color: #002200;">&#93;</span>;
        <span style="color: #a61390;">return</span> ISyncSessionDriverChangeError;
      <span style="color: #002200;">&#125;</span>
      <span style="color: #002200;">&#91;</span>record setRecordIdentifier<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>change recordIdentifier<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
      <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self recordLookup<span style="color: #002200;">&#93;</span> setObject<span style="color: #002200;">:</span>record forKey<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>change recordIdentifier<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
      <span style="color: #a61390;">break</span>;
    <span style="color: #a61390;">case</span> ISyncChangeTypeModify<span style="color: #002200;">:</span>
      record <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self recordLookup<span style="color: #002200;">&#93;</span> objectForKey<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>change recordIdentifier<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
      <span style="color: #a61390;">break</span>;
    <span style="color: #a61390;">default</span><span style="color: #002200;">:</span>
      errDict <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;Unknown type&quot;</span>
                                            forKey<span style="color: #002200;">:</span>NSLocalizedDescriptionKey<span style="color: #002200;">&#93;</span>;
      <span style="color: #002200;">*</span>err <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSError</span> errorWithDomain<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;CIMGF&quot;</span> code<span style="color: #002200;">:</span><span style="color: #2400d9;">8001</span> userInfo<span style="color: #002200;">:</span>errDict<span style="color: #002200;">&#93;</span>;
      <span style="color: #a61390;">return</span> ISyncSessionDriverChangeError;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSDictionary</span> <span style="color: #002200;">*</span>changeDict <span style="color: #a61390;">in</span> <span style="color: #002200;">&#91;</span>change changes<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>action <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>changeDict valueForKey<span style="color: #002200;">:</span>ISyncChangePropertyActionKey<span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>name <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>changeDict valueForKey<span style="color: #002200;">:</span>ISyncChangePropertyNameKey<span style="color: #002200;">&#93;</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>kRecordEntityName<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      <span style="color: #a61390;">continue</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>action isEqualToString<span style="color: #002200;">:</span>ISyncChangePropertyClear<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      <span style="color: #002200;">&#91;</span>record setNilValueForKey<span style="color: #002200;">:</span>name<span style="color: #002200;">&#93;</span>;
      <span style="color: #a61390;">continue</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #a61390;">id</span> value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>changeDict valueForKey<span style="color: #002200;">:</span>ISyncChangePropertyValueKey<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>record setValue<span style="color: #002200;">:</span>value forKey<span style="color: #002200;">:</span>name<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#91;</span>record setUpdated<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">return</span> ISyncSessionDriverChangeAccepted;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>In this method we use a switch to determine what type of change that it is.  If it is a delete we remove the record from our global store and return happy.  If it is an add then we create a new empty object and set the recordIdentifier.  Lastly, if it is a change we retrieve the record from our global store.</p>

<p>Once the object that is going to be changed has been referenced we loop through the changes which are stored in an array inside of the ISyncChange object.  Each object in the array is a dictionary containing up three values.  The first value has a key of ISyncChangePropertyActionKey and the value can either be ISyncChangePropertySet or ISyncChangePropertyClear.  If it is a clear then we are to set the property to nil.  Otherwise we change the property to the value stored under key ISyncChangePropertyValueKey.  The name of the property is stored under the key ISyncChangePropertyNameKey.  If our properties use the same name as the sync objects they represent (and in our case they do) then this step is performed in a loop using KVC to update each property.</p>

<p>Once we have updated the object we return ISyncSessionDriverChangeAccepted to let the sync engine know that everything is happy.  We could have returned ISyncSessionDriverChangeIgnored or ISyncSessionDriverChangeRejected if we did not accept the change for some reason.  In either of those cases the object and its changes would not be sent to us again unless it changed in the future.  Lastly, if there is a problem, we can return ISyncSessionDriverChangeError if there was an error.  If we return that, however, the sync engine expects us to populate the NSError pointer before returning.</p>

<p>There are two other pointers that get passed in that should be mentioned.  The first one, called outRecordIdentifier in this example is used in the case where we do not want to use the recordIdentifier being passed to us.  Perhaps we have our own internal schema or we want to reference this record by another identifier.  If we set this pointer then the Truth will remember that change and use the new identifier in the future when talking to us.  It will not use this new identifier when talking to anyone else though.  This is useful when syncing with a database that uses something other than a guid for uniqueness.  The second one, called outRecord in this example, is used to update the object.  Perhaps we had a field on new records or change a field; in either case those changes can be sent back to the Truth via this pointer.</p>

<h3>Other Data Source methods</h3>

<p>That is the major points of a sync.  We of course have a lot more flexibility to cover edge cases and we can make changes at any step in the process via the delegate methods but those are the points of contact for passing data back and forth.  Other than those complicated touch points, there are a few other methods that need to be implemented to make a sync work.  Those methods are more administrative and far less complicated.</p>

<ul>
  <li>clientIdentifier<br/>
    This is the unique string that identifies this client to the Truth.  I like to use the bundle identifier here just to make things simple.</li>
  <li>schemaBundleURLs<br/>
    This method returns an array of NSURL objects.  Each NSURL object points to a schema either on disk or on the net that describes the data to be stored in the Truth.  If we are creating a new set of data then we would need to generate a schema (and there is a template in Xcode for that purpose).  If not then we need to reference the existing schema.</li>
  <li>entityNamesToSync<br/>It is not necessary to sync every entity in a schema (although in our case we do since there are only two).  If we only care about a subset of the data then we can request to sync only those entities we care about.  In any case we pass back an array of strings here to let the sync engine know which entities we care about.</li>
  <li>preferredSyncModeForEntityName<br/>A fast sync is always the goal.  However if we need to refresh an object or perform a slow sync (useful when a large amount of data has changed or we lost our copy of the data) then this is the method that determines it.  This method will be called once for each entity we want to sync.</li>
  <li>clientDescriptionURL<br/>The client description is a plist file that describes this client to the sync engine.  For example, the icon used in dialogs is defined in this plist along with the human readable name of the sync client, etc.  Also in this plist we define what properties of each entity we want synced.  If we only want a subset of the entities we can control that here.</li>
</ul>

<h3>Conclusion</h3>

<p>I would not be at all surprised if that was as clear as mud.  The sync services framework is complicated, no doubt about that.  That complication has a purpose though, it is incredibility powerful as well.  Now that I have scratched the surface in this article I will be adding other articles to explain some of the more complicated aspects such as adding properties to an existing schema, mid-sync data changing and more.</p>

<p>If a part of this is unclear, please post a comment and I will update it to help clarify.  I would also recommend downloading the example application that is attached as I find the code much easier to understand.</p>

<p><center></p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2008/08/syncservicestutoral1.zip" title="Sync Services Tutorial 1"><img src="http://www.cimgf.com/wp-content/uploads/2008/03/xcode.png" alt="xcode.png" border="0" width="64"/><br/>Sync Services Tutorial 1</a></a></p>

<p></center></p>

<p><small>1. There is an option to have a helper tool that sync services will run when your application is not running but that is beyond the scope of this article.</small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/08/27/cocoa-tutorial-sync-services-without-core-data/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Cocoa Tutorial: C# LINQ Or Cocoa Key Paths And NSPredicate</title>
		<link>http://www.cimgf.com/2008/08/24/cocoa-tutorial-c-linq-or-cocoa-key-paths-and-nspredicate/</link>
		<comments>http://www.cimgf.com/2008/08/24/cocoa-tutorial-c-linq-or-cocoa-key-paths-and-nspredicate/#comments</comments>
		<pubDate>Sun, 24 Aug 2008 05:06:56 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=172</guid>
		<description><![CDATA[I think it may be helpful to demonstrate how to perform certain tasks in Cocoa from the perspective of a Windows programmer. And considering that I was one, it seems that I may be able to help shine some light on some of the issues that programmers face when coming over to the Mac platform. [...]]]></description>
			<content:encoded><![CDATA[<p>I think it may be helpful to demonstrate how to perform certain tasks in Cocoa from the perspective of a Windows programmer. And considering that I was one, it seems that I may be able to help shine some light on some of the issues that programmers face when coming over to the Mac platform. In this post I want to highlight one of Objective-C&#8217;s coolest features, key-value coding, in light of a Microsoft technology that was introduced in the most recent edition of the .NET framework (v3.5).</p>

<p>Microsoft&#8217;s <em>new</em> technology called LINQ, which stands for <a href="http://msdn.microsoft.com/en-us/vbasic/aa904594.aspx">Language Integrated Query</a> provides a way for developers to massage data collections using a SQL-like syntax that is built right into the language. You can perform simple data queries 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
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">List products <span style="color: #008000;">=</span> GetProductList<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
var soldOutProducts <span style="color: #008000;">=</span>
    from p <span style="color: #0600FF;">in</span> products
    where p.<span style="color: #0000FF;">UnitsInStock</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span>
    select p<span style="color: #008000;">;</span>
&nbsp;
Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Sold out products:&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>var product <span style="color: #0600FF;">in</span> soldOutProducts<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;{0} is sold out!&quot;</span>, product.<span style="color: #0000FF;">ProductName</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>


<p>Notice how it has a very SQL like syntax. It&#8217;s actually very powerful and robust. There are a lot of capabilities. Take a look at the <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx">101 LINQ Samples</a> page if you would like to see more examples. What&#8217;s most interesting to me though is that the ideas behind this technology are not new.</p>

<p>If you&#8217;re new to Cocoa, you&#8217;ve probably heard of key-value coding and have probably even worked through some examples of its use without really understanding it. While the usage is different between the two, these technologies provide similar capabilities. Objective-C just had them first.
<span id="more-172"></span></p>

<h2>Key Paths Rule</h2>

<p>Since OS X, the first version, key paths have been an integral part of data access and manipulation. Given an array or dictionary of objects you can filter your data down to a more specific data set. Your array doesn&#8217;t need to <em>know</em> anything about your data objects within the array or dictionary as the fields can be accessed by name. Have you ever seen syntax like this in Objective-C and wondered what it is?</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;"><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>lastNames <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>customers valueForKeyPath<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;lastName&quot;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>Say you have declared a <em>Customer</em> class 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: #a61390;">@interface</span> Customer <span style="color: #002200;">:</span> <span style="color: #400080;">NSObject</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>firstName;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>lastName;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>emailAddress;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>You declare some of the customer objects and add them to an array.</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;">Customer <span style="color: #002200;">*</span>bob <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>Customer alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>bob setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Bob&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;firstName&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>bob setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Smith&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;lastName&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>bob setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;bob@somedomain.com&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;emailAddress&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
Customer <span style="color: #002200;">*</span>carol <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>Customer alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>carol setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Carol&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;firstName&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>carol setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Jones&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;lastName&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>carol setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;carol@somedomain.com&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;emailAddress&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
Customer <span style="color: #002200;">*</span>wilma <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>Customer alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>wilma setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Wilma&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;firstName&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>wilma setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Baker&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;lastName&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>wilma setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;wilma@somedomain.com&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;emailAddress&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
customers <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;">NSMutableArray</span> alloc<span style="color: #002200;">&#93;</span> initWithObjects<span style="color: #002200;">:</span>bob, carol, wilma, <span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span> retain<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<blockquote><strong>Note:</strong> I could declare some field accessors for the Customer object which would allow you to get and set field values, but since this post is largely about key-value coding, I figured it would makes sense to demonstrate the full key-value coding way. There is no concept of private variable in Objective-C, so we can simply call <em>- setValue: forKey:</em> to set our fields.</blockquote>

<p>So if you recall this code from above:</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;"><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>lastNames <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>customers valueForKeyPath<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;lastName&quot;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>you can see that once <em>-valueForKeyPath</em> gets called on the customers array, the <em>NSArray</em> <em>lastNames</em> would now contain a list of all of the last names in the customers array.</p>

<p><pre>
(
    Smith,
    Jones,
    Baker
)
</pre></p>

<p>Ok, so that might only be slightly helpful, but keep in mind that you can filter this way as many times on the same array or a filtered array as you need to&#8211;not to mention that this capability has been around in OS X since 10.0. That&#8217;s right&#8211;ten dot oh; the first version of OS X. By time OS X 10.4 Tiger came around in 2005, this capability had improved significantly. Objective-C now had a way to use set and array operators that allow you to filter your results further and more efficiently.</p>

<h2>Set and Array Operators</h2>

<p>You can find all of the details that you might need to take advantage of these key path operators in the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/Concepts/ArrayOperators.html#//apple_ref/doc/uid/20002176">Key Value Coding Programming Guide</a>. Read it. It&#8217;s very helpful and comprehensive. In essence what these operators provide is a way to get a count, sum, average, max, min, distinct arrays, and arrays of joined arrays based on simple key path syntax.</p>

<p>Say you were interested in the average string length of the email addresses of all of your customers (not terribly useful, but oh so demonstrative). You could get that using this call.</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;"><span style="color: #002200;">&#91;</span>customers valueForKeyPath<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;@avg.emailAddress.length&quot;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>Keep in mind that the length field is not some special syntax but rather simply a key-value coding compliant variable in an <em>NSString</em> object which is what <em>emailAddress</em> is.</p>

<p>The result of the code above returns the average email string length as an NSNumber. In my example code from above, this returns 19 for the NSNumber value.</p>

<h2>But Wait! There&#8217;s More! NSPredicate</h2>

<p>If you need to filter your array even further, you can do this simply by using an <em>NSPredicate</em>. Scott Stevenson has a short and sweet blog post that demonstrates clearly how to use an <em>NSPredicate</em> on an array at his <a href="http://theocacao.com/document.page/346">Theocacao: Using NSPredicate to Filter an NSArray</a>. I&#8217;ll make his code conform to our example code here.</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: #400080;">NSPredicate</span> <span style="color: #002200;">*</span>predicate;
predicate <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;emailAddress.length &gt; 18&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #400080;">NSArray</span>  <span style="color: #002200;">*</span>longEmailAddresses <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>customers filteredArrayUsingPredicate<span style="color: #002200;">:</span>predicate<span style="color: #002200;">&#93;</span>; 
&nbsp;
NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Email Addresses Longer Than 18 Chars: %@&quot;</span>, longEmailAddresses<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>


<p>The array <em>longEmailAddresses</em> now contains two <em>Customer</em> objects for the two customers who have email address string lengths greater than 18 characters.</p>

<p>But really that&#8217;s just the beginning. You can find all you need to know about Predicates in the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/Predicates/predicates.html">Predicate Programming Guide</a> at the Apple Developer site. You&#8217;ll see that you can combine the set and array operator syntax with an NSPredicate to get pretty much any type of data query filter you can imagine. As an example, say you want to get an array of all of the customers who&#8217;s email addresses use the same domain name. The code would go like this.</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;">predicate <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;emailAddress endswith '@somedomain.com'&quot;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>This will return all of our customer objects in the array because they all have the same domain name, however, if you change one of the email addresses, say for Carol.</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;"><span style="color: #002200;">&#91;</span>carol setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;carol@otherdomain.com&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;emailAddress&quot;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>you will notice that the array will now only contain the two customer objects who&#8217;s domain names are <em>somedomain.com</em>.</p>

<h2>So What About LINQ</h2>

<p>LINQ is actually very interesting technology. It allows you to run these types of inline queries on different types of data sets including XML and SQL databases. To ask the question &#8220;which is better&#8221; is really just an invitation to argue, so I won&#8217;t claim that the Cocoa is necessarily better. It has, however, been around longer and has provided these capabilities since the early days. So the point is that if you&#8217;ve seen this &#8220;new-fangled technology&#8221; from Microsoft and are wondering if you can do the same in Cocoa, the answer is a resounding <em>yes</em>. Data filtering as part of the language is cool technology, but it is most certainly not a Microsoft invention. All props to <a href="http://en.wikipedia.org/wiki/Anders_Hejlsberg">Anders Hejlsberg</a>, the creator of C# and LINQ. He&#8217;s an amazing engineer and has brought a lot of great insight to Microsoft on behalf of developers. If you have to develop applications on Windows, be thankful for this guy. Without him, <a href="http://en.wikipedia.org/wiki/Microsoft_Foundation_Class_Library">things would be a lot worse</a>.</p>

<p>If you are, however, free to code in Cocoa, then embrace the key-value coding methodology. It&#8217;s very powerful and gives you flexibility that helps you to reduce the amount of code you need to write.</p>

<h2>Conclusion</h2>

<p>As a Objective-C/Cocoa developer, you need to get your key-value coding game on. It&#8217;s a very powerful component of the language and once you understand it, you&#8217;ll be able to not only utilize it where its available in the API, but you&#8217;ll be able to put it to use in your own objects. Until next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/08/24/cocoa-tutorial-c-linq-or-cocoa-key-paths-and-nspredicate/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
