<?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>Cocoanetics &#187; Recipes</title>
	<atom:link href="http://www.cocoanetics.com/category/recipes/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cocoanetics.com</link>
	<description>Our DNA is written in Objective-C</description>
	<lastBuildDate>Sun, 20 May 2012 14:40:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Twitter.framework Tutorial</title>
		<link>http://www.cocoanetics.com/2012/05/twitter-framework-tutorial/</link>
		<comments>http://www.cocoanetics.com/2012/05/twitter-framework-tutorial/#comments</comments>
		<pubDate>Sun, 20 May 2012 14:40:36 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=6356</guid>
		<description><![CDATA[I have this idea for an app that I would totally use myself. You know I started XcodeJobs.com and the @XcodeJobs twitter feed to go with it to have a channel to retweet all the iOS-related job offerings that flow before my very eyes. For the site I&#8217;ve been talking to people to create a login for themselves and post their jobs self-servingly. For the twitter feed I&#8217;ve been using the Twitter search features with a variety of search terms to find tweets where company owners of the developers themselves are tweeting about job postings. Now the reality of the matter is that most of all Tweets are from recruiters, agencies, job sites and other kinds of services that a self-respecting iOS developer does not want anything to do with. So right now I&#8217;m manually filtering tweets. There are a variety of criteria that I want to be able to combine to end up at the real good retweet-worthy tweets. &#160; For example I would do a search for &#8220;hiring iOS&#8221; &#8230; Criteria for exclusion might include: Jack Patrick I found to be a recruiter Jobely.com and Jobrep.com are examples for job websites The jobmakesfun is pointing to a Freelancer site with a ridiculous project description. The one for Viki is pointing to a dubious URL that does not seem to correspond with the hiring company. On the above screenshot the one tweet by Fable Technologies is the only one I deemed worthy of retweeting. It does not contain link bait, is by the guys for themselves, no commercially interested middle man in sight and they are so daring as to even post their e-mail address. All of these manual steps surely can be automated. I&#8217;m envisioning several black lists of twitter accounts that I want to ignore. And the second big category would be to ignore tweets that are leading to job sites (like Bullhorn Reach) or agencies. The user (i.e. myself) could configure multiple elaborate search queries and have the app filter out all the crap. So ideally this would leave us with the true gems of Twitterdom. What Twitter Engine to Use? So I sat down in front of my home iMac and started to think to myself: &#8220;OMG that will be hell of a job. Maybe I should go look for a good Twitter engine to use first.&#8221; The reason for this train of thought was that nowadays most of the interaction with the Twitter REST API has to be authenticated via OAuth. Which is why there are a bunch of OAuth frameworks in the wild, including one from Google because their APIs are OAuth-heavy as well. OAuth basically works by having a secret token that you have to add to all URL requests that need authentication. Of course one could program this from scratch but you&#8217;d certainly spend quite some time on this. Even using a third party OAuth library would not be straightforward because of the time it takes to figure out how to include it in your app. All of these reasons would make this small project unrealistic for a couple of stolen hours on a Sunday. Some people recommended MGTwitterEngine, but then it dawned on me that there was something new that Apple had introduced with iOS 5. So I checked the SDK documentation and &#8211; indeed! &#8211; besides the TWTweetComposeViewController that everybody now knows about there is a second class that is exactly what we need: TWRequest. Tw&#8230;TW&#8230;TWRequest? Hidden behind the simplest of names is a wrapper that you can do any kind of request with. Think of it as a block-based wrapper around NSURLConnection with all the trimmings needed to also do authentication where necessary. Let&#8217;s dive right in, and start by doing a simple search. We added the Twitter.framework to the linked libraries and in the class where we want to call TWRequest we added &#60;Twitter/Twitter.h&#62;. I prefer to put that in the PCH file so that it is available everywhere without needing an extra inclusion of the header. The search itself is deceptively simple: NSURL *searchURL = &#91;NSURL URLWithString:@&#34;http://search.twitter.com/search.json&#34;&#93;; NSDictionary *parameters = &#91;NSDictionary dictionaryWithObject:@&#34;hiring ios&#34; forKey:@&#34;q&#34;&#93;; TWRequest *request = &#91;&#91;TWRequest alloc&#93; initWithURL:searchURL parameters:parameters requestMethod:TWRequestMethodGET&#93;; &#160; &#91;request performRequestWithHandler:^&#40;NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error&#41; &#123; if &#40;responseData&#41; &#123; NSError *parseError = nil; id json = &#91;NSJSONSerialization JSONObjectWithData:responseData options:0 error:&#38;amp;parseError&#93;; &#160; if &#40;!json&#41; &#123; NSLog&#40;@&#34;Parse Error: %@&#34;, parseError&#41;; &#125; else &#123; NSLog&#40;@&#34;%@&#34;, json&#41;; &#125; &#125; else &#123; NSLog&#40;@&#34;Request Error: %@&#34;, &#91;error localizedDescription&#93;&#41;; &#125; &#125;&#93;; To perform a Twitter request you need to have a couple of ingredients, which you can glean from the Twitter API Documentation, for example for the search function. We needed the URL which is a composite of: the so-called endpoint: http://search.twitter.com the method name: search the response data format: json The parameters need to be provided in a dictionary which [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/05/twitter-framework-tutorial/"></g:plusone></div><p>I have this idea for an app that I would totally use myself. You know I started <a href="http://www.xcodejobs.com">XcodeJobs.com</a> and the <a href="http://www.twitter.com/xcodejobs">@XcodeJobs</a> twitter feed to go with it to have a channel to retweet all the iOS-related job offerings that flow before my very eyes. For the site I&#8217;ve been talking to people to create a login for themselves and post their jobs self-servingly. For the twitter feed I&#8217;ve been using the Twitter search features with a variety of search terms to find tweets where company owners of the developers themselves are tweeting about job postings.</p>
<p>Now the reality of the matter is that most of all Tweets are from recruiters, agencies, job sites and other kinds of services that a self-respecting iOS developer does not want anything to do with. So right now I&#8217;m manually filtering tweets. There are a variety of criteria that I want to be able to combine to end up at the real good retweet-worthy tweets.</p>
<p><span id="more-6356"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>For example I would do a search for &#8220;hiring iOS&#8221; &#8230;</p>
<p><a href="http://www.cocoanetics.com/files/AtVBXB2CAAIwn9I.png-large.png"><img class="alignnone  wp-image-6357" title="Filtering Fun" src="http://www.cocoanetics.com/files/AtVBXB2CAAIwn9I.png-large.png" alt="" width="614" height="461" /></a></p>
<p>Criteria for exclusion might include:</p>
<ul>
<li>Jack Patrick I found to be a recruiter</li>
<li>Jobely.com and Jobrep.com are examples for job websites</li>
<li>The jobmakesfun is pointing to a Freelancer site with a ridiculous project description.</li>
<li>The one for Viki is pointing to a dubious URL that does not seem to correspond with the hiring company.</li>
</ul>
<p>On the above screenshot the one tweet by Fable Technologies is the only one I deemed worthy of retweeting. It does not contain link bait, is by the guys for themselves, no commercially interested middle man in sight and they are so daring as to even post their e-mail address.</p>
<p>All of these manual steps surely can be automated. I&#8217;m envisioning several black lists of twitter accounts that I want to ignore. And the second big category would be to ignore tweets that are leading to job sites (like Bullhorn Reach) or agencies. The user (i.e. myself) could configure multiple elaborate search queries and have the app filter out all the crap. So ideally this would leave us with the true gems of Twitterdom.</p>
<h3>What Twitter Engine to Use?</h3>
<p>So I sat down in front of my home iMac and started to think to myself: <em>&#8220;OMG that will be hell of a job. Maybe I should go look for a good Twitter engine to use first.&#8221;</em></p>
<p>The reason for this train of thought was that nowadays most of the interaction with the Twitter REST API has to be authenticated via OAuth. Which is why there are a bunch of OAuth frameworks in the wild, including one from Google because their APIs are OAuth-heavy as well. OAuth basically works by having a secret token that you have to add to all URL requests that need authentication. Of course one could program this from scratch but you&#8217;d certainly spend quite some time on this. Even using a third party OAuth library would not be straightforward because of the time it takes to figure out how to include it in your app.</p>
<p>All of these reasons would make this small project unrealistic for a couple of stolen hours on a Sunday.</p>
<p>Some people recommended MGTwitterEngine, but then it dawned on me that there was something new that Apple had introduced with iOS 5. So I checked the SDK documentation and &#8211; indeed! &#8211; besides the TWTweetComposeViewController that everybody now knows about there is a second class that is exactly what we need: <strong>TWRequest</strong>.</p>
<h3>Tw&#8230;TW&#8230;TWRequest?</h3>
<p>Hidden behind the simplest of names is a wrapper that you can do any kind of request with. Think of it as a block-based wrapper around NSURLConnection with all the trimmings needed to also do authentication where necessary.</p>
<p>Let&#8217;s dive right in, and start by doing a simple search. We added the Twitter.framework to the linked libraries and in the class where we want to call TWRequest we added &lt;Twitter/Twitter.h&gt;. I prefer to put that in the PCH file so that it is available everywhere without needing an extra inclusion of the header.</p>
<p>The search itself is deceptively simple:</p>

<div class="wp_codebox"><table><tr id="p63566"><td class="code" id="p6356code6"><pre class="objc" style="font-family:monospace;"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/"><span style="color: #400080;">NSURL</span></a> <span style="color: #002200;">*</span>searchURL <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/"><span style="color: #400080;">NSURL</span></a> URLWithString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;http://search.twitter.com/search.json&quot;</span><span style="color: #002200;">&#93;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/"><span style="color: #400080;">NSDictionary</span></a> <span style="color: #002200;">*</span>parameters <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/"><span style="color: #400080;">NSDictionary</span></a> dictionaryWithObject<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;hiring ios&quot;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;q&quot;</span><span style="color: #002200;">&#93;</span>;
TWRequest <span style="color: #002200;">*</span>request <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>TWRequest alloc<span style="color: #002200;">&#93;</span> initWithURL<span style="color: #002200;">:</span>searchURL parameters<span style="color: #002200;">:</span>parameters requestMethod<span style="color: #002200;">:</span>TWRequestMethodGET<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>request performRequestWithHandler<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/"><span style="color: #400080;">NSData</span></a> <span style="color: #002200;">*</span>responseData, <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPURLResponse_Class/"><span style="color: #400080;">NSHTTPURLResponse</span></a> <span style="color: #002200;">*</span>urlResponse, <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/"><span style="color: #400080;">NSError</span></a> <span style="color: #002200;">*</span>error<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>responseData<span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/"><span style="color: #400080;">NSError</span></a> <span style="color: #002200;">*</span>parseError <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
        <span style="color: #a61390;">id</span> json <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>NSJSONSerialization JSONObjectWithData<span style="color: #002200;">:</span>responseData options<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> error<span style="color: #002200;">:&amp;</span>amp;parseError<span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>json<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;Parse Error: %@&quot;</span>, parseError<span style="color: #002200;">&#41;</span>;
        <span style="color: #002200;">&#125;</span>
        <span style="color: #a61390;">else</span>
        <span style="color: #002200;">&#123;</span>
            NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>, json<span style="color: #002200;">&#41;</span>;
        <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#125;</span>
    <span style="color: #a61390;">else</span>
    <span style="color: #002200;">&#123;</span>
        NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Request Error: %@&quot;</span>, <span style="color: #002200;">&#91;</span>error localizedDescription<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>To perform a Twitter request you need to have a couple of ingredients, which you can glean from the <a href="https://dev.twitter.com/docs/api">Twitter API Documentation</a>, for example for the <a href="https://dev.twitter.com/docs/api/1/get/search">search</a> function.</p>
<p>We needed the URL which is a composite of:</p>
<ul>
<li>the so-called endpoint: <strong>http://search.twitter.com</strong></li>
<li>the method name: <strong>search</strong></li>
<li>the response data format: <strong>json</strong></li>
</ul>
<p>The parameters need to be provided in a dictionary which is also straightforward, the keys are the parameter names and the values are the parameter values. Also we don&#8217;t need authentication for search, in fact it is not even supported according to the Twitter docs. This is to make it impossible for Twitter to track you based on what you search for&#8230; unlike Google.</p>
<p>TWRequests supports the three HTTP verbs GET, POST and DELETE. The documentation tells you which one to use. Note that different API functions might have different end points.</p>
<p>We could have also chosen xml format for the response format, but there is no simple way to transform that into something useful for us. NSXMLParser works event-based and we would have to do some work to get it into a structure. The second ingredient that we need is also new with iOS 5, Apple provides a handy high performance class to serialize and deserialize JSON data.By passing the responds of the TWRequest into <strong>NSJSONSerialization</strong> we get an NSDictionary containing the parsed JSON. With JSON and the de-serialization method provided we get a dictionary which is way more convenient.</p>
<p>If the deserialization worked you get a non-nil result, looking like this:</p>

<div class="wp_codebox"><table><tr id="p63567"><td class="code" id="p6356code7"><pre class="json" style="font-family:monospace;">{
    &quot;completed_in&quot; = &quot;0.027&quot;;
    &quot;max_id&quot; = 204150933297446912;
    &quot;max_id_str&quot; = 204150933297446912;
    &quot;next_page&quot; = &quot;?page=2&amp;amp;max_id=204150933297446912&amp;amp;q=hiring%20ios&quot;;
    page = 1;
    query = &quot;hiring+ios&quot;;
    &quot;refresh_url&quot; = &quot;?since_id=204150933297446912&amp;amp;q=hiring%20ios&quot;;
    results =     (
                {
            &quot;created_at&quot; = &quot;Sun, 20 May 2012 10:05:50 +0000&quot;;
            &quot;from_user&quot; = &quot;fun_programming&quot;;
            &quot;from_user_id&quot; = 282845320;
            &quot;from_user_id_str&quot; = 282845320;
            &quot;from_user_name&quot; = jobmakesfun;
            geo = &quot;&quot;;
            id = 204150933297446912;
            &quot;id_str&quot; = 204150933297446912;
            &quot;iso_language_code&quot; = en;
            metadata =             {
                &quot;result_type&quot; = recent;
            };
            &quot;profile_image_url&quot; = &quot;http://a0.twimg.com/profile_images/1313148959/jobs_normal.gif&quot;;
            &quot;profile_image_url_https&quot; = &quot;https://si0.twimg.com/profile_images/1313148959/jobs_normal.gif&quot;;
            source = &quot;&amp;lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&amp;gt;twitterfeed&amp;lt;/a&amp;gt;&quot;;
            text = &quot;#ipad #project iOS Game Side Scrolling Battle by olimoli123: I require someone to make a game like ... http://t.co/LNqWsmLs #dev #hiring&quot;;
            &quot;to_user&quot; = &quot;&quot;;
            &quot;to_user_id&quot; = 0;
            &quot;to_user_id_str&quot; = 0;
            &quot;to_user_name&quot; = &quot;&quot;;
        },
                {
            &quot;created_at&quot; = &quot;Sun, 20 May 2012 08:18:14 +0000&quot;;
            &quot;from_user&quot; = XcodeJobs;
            &quot;from_user_id&quot; = 539747758;
            &quot;from_user_id_str&quot; = 539747758;
            &quot;from_user_name&quot; = &quot;Xcode Jobs&quot;;
            geo = &quot;&quot;;
            id = 204123856812785665;
            &quot;id_str&quot; = 204123856812785665;
            &quot;iso_language_code&quot; = pl;
            metadata =             {
                &quot;result_type&quot; = recent;
            };
            &quot;profile_image_url&quot; = &quot;http://a0.twimg.com/profile_images/1988345754/xcode-twitter_normal.png&quot;;
            &quot;profile_image_url_https&quot; = &quot;https://si0.twimg.com/profile_images/1988345754/xcode-twitter_normal.png&quot;;
            source = &quot;&amp;lt;a href=&quot;http://angel.co&quot; rel=&quot;nofollow&quot;&amp;gt;AngelList&amp;lt;/a&amp;gt;&quot;;
            text = &quot;RT @CardFlick: CardFlick (@CardFlick) is hiring a iOS Engineer http://t.co/O7Wf0gtw&quot;;
            &quot;to_user&quot; = &quot;&quot;;
            &quot;to_user_id&quot; = 0;
            &quot;to_user_id_str&quot; = 0;
            &quot;to_user_name&quot; = &quot;&quot;;
        },...</pre></td></tr></table></div>

<p>We get the tweets in an NSArray below the &#8220;results&#8221; key, each tweet being represented by an NSDictionary. If we wanted to refresh the contents of this query we could use the value stated in &#8220;refresh_url&#8221;. Then we would only see tweets that were made after the ones we had already gotten here.</p>
<p>Also results are paginated. To retrieve subsequent pages there is a &#8220;next_page&#8221; value that would get us those. The default is to return 15 tweets per &#8220;page&#8221;. We could easily also increase this number by passing it as the optional &#8220;rpp&#8221; (results per page) parameter.</p>
<h3>Later the same day &#8230;</h3>
<p>I&#8217;m skipping over the part where I&#8217;m merging the result dictionary into a CoreData database and using an NSFetchedResultsController to display the tweets. That is a different story which I shall treat another day. Let&#8217;s just say, I got it to display in a very basic form and pushing a refresh button would redo the same query and merge the results into a database.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-20-um-14.20.31.png"><img class="alignnone size-full wp-image-6360" title="Simple Twitter DB" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-20-um-14.20.31.png" alt="" width="380" height="241" /></a></p>
<p>After getting all the basics wired up (CoreData Stack, methods to query by ID for user and message, merging function, table view controller, fetched results controller) I ended up with a view like this:</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-20-um-14.25.20.png"><img class="alignnone  wp-image-6361" title="Basic Twitter UI" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-20-um-14.25.20.png" alt="" width="238" height="446" /></a></p>
<p>It is immediately apparent from this that we are seeing only tweets that we want to get rid of. 4 of these Twitter accounts would be blacklisted because of the reasons stated above. Also my own tweets are visible as they came from my own account and start with RT, those where the job tweets I had retweeted. OMG the amount of time this tool will save me not having to visually scan through all of this&#8230;</p>
<p>But like every TV cook I&#8217;ve already prepared this step as the details are of no interest for this tutorial. I added a long press gesture recognizer to each cell and a red &#8220;Blacklist&#8221; button that allows me to mark the TwitterUser as blacklisted and remove his tweets from the database. This results in a tremendous improvement.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-20-um-15.03.47.png"><img class="alignnone  wp-image-6363" title="Basic Twitter UI, now cleaned up" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-20-um-15.03.47.png" alt="" width="238" height="446" /></a></p>
<p>Oh, look! Fable Technologies is at the top after having blacklisted all the clutter. They should pay me a referral fee for all this free advertising!</p>
<p>Now for the hard part of this tutorial. Now that we have leaned up the result, we also want to be able to retweet individual messages and of course somehow know if we have done so already to prevent a double-retweeting. Unfortunately there does not seem to be an easy we to get the retweet info included in the search results.</p>
<h3>Dealing with Accounts</h3>
<p>In order to do something that requires authentication we need to ask the global account store for a list of Twitter accounts and have the user pick one. First we add the Accounts.framework in our build phases. Then we add &lt;Accounts/Accounts.h&gt; to our PCH file.</p>
<p>The first time we want access to a given account type (as of iOS 5 only Twitter is supported) we need to ask the user&#8217;s permission. Subsequently we can query the ACAccountType if permission has already been given.</p>

<div class="wp_codebox"><table><tr id="p63568"><td class="code" id="p6356code8"><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>account<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIBarButtonItem <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>sender
<span style="color: #002200;">&#123;</span>
    ACAccountStore <span style="color: #002200;">*</span>accountStore <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>ACAccountStore alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    ACAccountType <span style="color: #002200;">*</span>accountType <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>accountStore accountTypeWithAccountTypeIdentifier<span style="color: #002200;">:</span>ACAccountTypeIdentifierTwitter<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>accountType accessGranted<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        <span style="color: #11740a; font-style: italic;">// have access already</span>
        <span style="color: #002200;">&#91;</span>self _showListOfTwitterAccountsFromStore<span style="color: #002200;">:</span>accountStore<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: #11740a; font-style: italic;">// need access first</span>
        <span style="color: #002200;">&#91;</span>accountStore requestAccessToAccountsWithType<span style="color: #002200;">:</span>accountType withCompletionHandler<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span> granted, <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/"><span style="color: #400080;">NSError</span></a> <span style="color: #002200;">*</span>error<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
&nbsp;
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>granted<span style="color: #002200;">&#41;</span>
            <span style="color: #002200;">&#123;</span>
                <span style="color: #002200;">&#91;</span>self _showListOfTwitterAccountsFromStore<span style="color: #002200;">:</span>accountStore<span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span>
            <span style="color: #a61390;">else</span>
            <span style="color: #002200;">&#123;</span>
                UIAlertView <span style="color: #002200;">*</span>alert <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIAlertView alloc<span style="color: #002200;">&#93;</span> initWithTitle<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Error&quot;</span> message<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Cannot link account without permission&quot;</span> delegate<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> cancelButtonTitle<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Ok&quot;</span> otherButtonTitles<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
                <span style="color: #002200;">&#91;</span>alert show<span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span>
        <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>There is no shared instance of the ACAccountStore, so we have to create our own with alloc/init. Then we create the ACAccountType for Twitter and check if we might already have access granted. If not then we ask for it passing a completion handler. For sake of simplicity I opted to just show an action sheet for all the configured accounts. This does not deal with the situation of no configured accounts.</p>

<div class="wp_codebox"><table><tr id="p63569"><td class="code" id="p6356code9"><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>_showListOfTwitterAccountsFromStore<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>ACAccountStore <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>accountStore
<span style="color: #002200;">&#123;</span>
    ACAccountType <span style="color: #002200;">*</span>accountType <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>accountStore accountTypeWithAccountTypeIdentifier<span style="color: #002200;">:</span>ACAccountTypeIdentifierTwitter<span style="color: #002200;">&#93;</span>;
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span>twitterAccounts <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>accountStore accountsWithAccountType<span style="color: #002200;">:</span>accountType<span style="color: #002200;">&#93;</span>;
&nbsp;
    UIActionSheet <span style="color: #002200;">*</span>actions <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIActionSheet alloc<span style="color: #002200;">&#93;</span> initWithTitle<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Choose Account to Use&quot;</span> delegate<span style="color: #002200;">:</span>self cancelButtonTitle<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Cancel&quot;</span> destructiveButtonTitle<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> otherButtonTitles<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
    actions.tag <span style="color: #002200;">=</span> <span style="color: #2400d9;">2</span>;
&nbsp;
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/"><span style="color: #400080;">NSMutableArray</span></a> <span style="color: #002200;">*</span>shownAccounts <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/"><span style="color: #400080;">NSMutableArray</span></a> array<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span>ACAccount <span style="color: #002200;">*</span>oneAccount <span style="color: #a61390;">in</span> twitterAccounts<span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>actions addButtonWithTitle<span style="color: #002200;">:</span>oneAccount.username<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span>shownAccounts addObject<span style="color: #002200;">:</span>oneAccount<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    _shownAccounts <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>shownAccounts copy<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span>actions showInView<span style="color: #002200;">:</span>self.view<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Since I don&#8217;t have any block-based action sheet handy I need to remember the list of accounts presented in _shownAccounts IVAR and then in the delegate method for the action sheet I can pick the correct one based on the index. The important thing here is that we end up with an instance of a ACAccount.</p>
<h3>Now Let&#8217;s Sign This&#8230;</h3>
<p>Let&#8217;s quickly check the <a href="https://dev.twitter.com/docs/api/1/post/statuses/retweet/%3Aid">Retweet API </a>and what we need to perform such a request.</p>
<p>Just like above for the search we need to construct a URL from these parts:</p>
<ul>
<li>the endpoint: <strong>http://api.twitter.com/1</strong></li>
<li>the method name: <strong>statuses/retweet</strong></li>
<li>the identifier of the tweet to retweet:<strong> some number</strong></li>
<li>the response data format: <strong>json</strong></li>
<li>no parameters necessary</li>
</ul>
<p>Here I stumbled across something that was not immediately obvious to me. You have to store the ACAccountStore in an instance variable. Otherwise the ACAccount&#8217;s ACAccountType will be released by the autorelease pool. At let&#8217;s that&#8217;s what happened to me, I got a memory exception and an authentication error in alternation. Could it be that there&#8217;s a bug in the Accounts framework? Seems to me that the accountType property of ACAccount should be a strong reference, but it isn&#8217;t.</p>
<p>But that aside, there&#8217;s no hurt making an IVAR for the account store, the function to retweet would then look like this:</p>

<div class="wp_codebox"><table><tr id="p635610"><td class="code" id="p6356code10"><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>_retweetMessage<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>TwitterMessage <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>message
<span style="color: #002200;">&#123;</span>
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>retweetString <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;http://api.twitter.com/1/statuses/retweet/%@.json&quot;</span>, message.identifier<span style="color: #002200;">&#93;</span>;
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/"><span style="color: #400080;">NSURL</span></a> <span style="color: #002200;">*</span>retweetURL <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/"><span style="color: #400080;">NSURL</span></a> URLWithString<span style="color: #002200;">:</span>retweetString<span style="color: #002200;">&#93;</span>;
    TWRequest <span style="color: #002200;">*</span>request <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>TWRequest alloc<span style="color: #002200;">&#93;</span> initWithURL<span style="color: #002200;">:</span>retweetURL parameters<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> requestMethod<span style="color: #002200;">:</span>TWRequestMethodPOST<span style="color: #002200;">&#93;</span>;
    request.account <span style="color: #002200;">=</span> _usedAccount;
&nbsp;
    <span style="color: #002200;">&#91;</span>request performRequestWithHandler<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/"><span style="color: #400080;">NSData</span></a> <span style="color: #002200;">*</span>responseData, <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPURLResponse_Class/"><span style="color: #400080;">NSHTTPURLResponse</span></a> <span style="color: #002200;">*</span>urlResponse, <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/"><span style="color: #400080;">NSError</span></a> <span style="color: #002200;">*</span>error<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>responseData<span style="color: #002200;">&#41;</span>
        <span style="color: #002200;">&#123;</span>
            <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/"><span style="color: #400080;">NSError</span></a> <span style="color: #002200;">*</span>parseError <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
            <span style="color: #a61390;">id</span> json <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>NSJSONSerialization JSONObjectWithData<span style="color: #002200;">:</span>responseData options<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> error<span style="color: #002200;">:&amp;</span>amp;parseError<span style="color: #002200;">&#93;</span>;
&nbsp;
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>json<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;Parse Error: %@&quot;</span>, parseError<span style="color: #002200;">&#41;</span>;
            <span style="color: #002200;">&#125;</span>
            <span style="color: #a61390;">else</span>
            <span style="color: #002200;">&#123;</span>
                NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>, json<span style="color: #002200;">&#41;</span>;
            <span style="color: #002200;">&#125;</span>
        <span style="color: #002200;">&#125;</span>
        <span style="color: #a61390;">else</span>
        <span style="color: #002200;">&#123;</span>
            NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Request Error: %@&quot;</span>, <span style="color: #002200;">&#91;</span>error localizedDescription<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
        <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>There are three differences here versus the search request. 1) this one is a POST, 2) there are no parameters and 3) we set the account property to the ACAccount we have selected earlier. And if this works we indeed see the retweets show up immediately.</p>
<p><a href="http://www.cocoanetics.com/files/AtWHHvPCQAAtm6u.png-large.png"><img class="alignnone  wp-image-6366" title="Tweets showing up" src="http://www.cocoanetics.com/files/AtWHHvPCQAAtm6u.png-large.png" alt="" width="614" height="461" /></a></p>
<p>If you get an authentication error, then there&#8217;s a problem with the ACAccount. If you get some error complaining that this cannot be done with the given tweet, then most likely you have already retweeted it before. And in case of success you get a response with some retweet status.</p>
<h3>Conclusion</h3>
<p>There are a couple more touches necessary to make this app really useful. For one, we also need to retrieve the timeline of own retweets to be able to mark the tweets we already looked at. Also the retweet response should somehow be used to mark the tweet as retweeted.</p>
<p>And of course the UI could use much more work. We want to asynchronously show the profile pictures, access and edit the blacklist, decode the shortened URLs and make a blacklist based on those and of course be able to specify multiple search query for a given topic. For the UI I&#8217;ll probably use my DTCoreText method that lets me render the tweets with interactive hyperlinks.</p>
<p>But the gist of this post is that if you know about the Twitter and the Account frameworks then it is quite easy to build your own specialized Twitter client. We can extend a heart-felt &#8220;Thank You!&#8221; to the engineers at Apple who built something as useful as these into the operating system. Interacting with Twitter couldn&#8217;t be easier!</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=6356&amp;md5=22829170047a27b41eabfd4044e3bf83" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/05/twitter-framework-tutorial/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F05%2Ftwitter-framework-tutorial%2F&amp;language=en_GB&amp;category=text&amp;title=Twitter.framework+Tutorial&amp;description=I+have+this+idea+for+an+app+that+I+would+totally+use+myself.+You+know+I+started+XcodeJobs.com+and+the+%40XcodeJobs+twitter+feed+to+go+with+it+to+have+a...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Resource Bundles</title>
		<link>http://www.cocoanetics.com/2012/05/resource-bundles/</link>
		<comments>http://www.cocoanetics.com/2012/05/resource-bundles/#comments</comments>
		<pubDate>Tue, 01 May 2012 08:45:20 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=6307</guid>
		<description><![CDATA[When shrink-wrapping your code for later reuse you inadvertenly will come into the situation that you have some resources (strings, XIBs, images et al) in your project that you also want to be reused. So what do you do? If only we had frameworks on iOS &#8230; then we could bundle the resources together with the code in a framework. But Apple does not want us to compile frameworks in Xcode since these could potentially contain code downloaded after the app review process. Popular projects like ShareKit or the Facebook iOS SDK have approached this dilemma by simply putting all resources into a folder, giving it the &#8220;.bundle&#8221; extension and instruct users of their SDK to also add this bundle to the &#8220;Copy Bundle Resources&#8221; step of their respective apps. In this here blog post I will show you a smarter way. &#160; There are several problems with having resources contained in a bundle and having this bundle be a member of any projects. Not Visible Xcode does not directly &#8220;see&#8221; the contents of the bundle, instead the pbxproj only contains a reference to the bundle folder. This causes trouble for apps like our Linguan that parses the project file to find strings (and soon XIB) files. It simply cannot see them. Here&#8217;s how it looks in the ShareKit project. If you ever see a x.bundle in a project you open, armed with the knowledge in this article, your reaction should be &#8220;that&#8217;s bad&#8221;. Of course the maintainers of these projects &#8220;have their reasons&#8221;. But I hope that by reading this you will agree with me that the reasons to not do it like this are better. Not Optimized Another issue is that this approach effectively disables the build time optimizations that Xcode carries out on the resources. strings files get converted into binary property lists XIB files get compiled into binary NIBs images get pngcrush-ed and many other actions for which there are build rules set up That means resources that are simply bundled (by means of copying them together) are slower and not optimized for the mobile devices. You probably wouldn&#8217;t notice that for only a hand full of items, but if you have a large number of resources then these delays will add up slowing down your app. And even if that does not bother you very much then the engineer inside of you should cringe. It just feels so dirty&#8230; Not Updating Another reason for why it is a bad idea to hide files from Xcode is that it simply won&#8217;t know to rebuild your app if you make a change in one of the files hidden in such a bundle. The Xcode build system has what is called dependencies. Implicit dependencies are source code files and resources that are part of certain targets. If such a dependence is modified then the incremental build process can determine which parts need to be re-compiled or re-optimized. Say you change something in a single .m file. Xcode will not rebuild the entire app, but only create the .o for this updated file and then link it with the previously built (and unchanged .o files). Same with resources. Xcode only replaces resources in the output product .app bundle if it knows they where modified. Resources in static bundles are invisible to Xcode and thus you always have to clean your build folder when doing a new build after changing them. Otherwise your updates will not propagate into your app. Enter the Resource Bundle Target Xcode, iOS and OS X have a mechanism to deal with folders that are looking like a single file but are actually containing multiple resources. This mechanism is modeled by the NSBundle class. You probably have worked with bundles before, namely the .app bundles that make up your app. Have you ever written [NSBundle mainBundle] before? I bet you did. For NSBundle to be able to manage bundles it requires a special info.plist inside the bundle that contains some meta information, like an internal identifier. But once you have the bundle set up correctly you have multiple great options for getting at the files as I will show you below. How to Set Up a Resource Bundle Product A resource bundle is a product that we will set up a target for. It just so happens that my DTPinLockController project is in need of some love, so it will serve as our example for this tutorial. As a first step I needed to move the files into the modern way of structuring my projects. That is, for component projects I have a Core and a Demo folder at the project root. Then each has a Source and a Resources sub-folder. DTPinLockController has XIBs, Images and Localizable.strings files. The source code goes into a Static Library [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/05/resource-bundles/"></g:plusone></div><p>When shrink-wrapping your code for later reuse you inadvertenly will come into the situation that you have some resources (strings, XIBs, images et al) in your project that you also want to be reused. So what do you do?</p>
<p>If only we had frameworks on iOS &#8230; then we could bundle the resources together with the code in a framework. But Apple does not want us to compile frameworks in Xcode since these could potentially contain code downloaded after the app review process.</p>
<p>Popular projects like <a href="https://github.com/ShareKit/ShareKit">ShareKit</a> or the <a href="https://github.com/facebook/facebook-ios-sdk">Facebook iOS SDK</a> have approached this dilemma by simply putting all resources into a folder, giving it the &#8220;.bundle&#8221; extension and instruct users of their SDK to also add this bundle to the &#8220;Copy Bundle Resources&#8221; step of their respective apps.</p>
<p>In this here blog post I will show you a smarter way.</p>
<p><span id="more-6307"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>There are several problems with having resources contained in a bundle and having this bundle be a member of any projects.</p>
<h3>Not Visible</h3>
<p>Xcode does not directly &#8220;see&#8221; the contents of the bundle, instead the pbxproj only contains a reference to the bundle folder. This causes trouble for apps like our <a href="http://www.cocoanetics.com/apps/linguan/">Linguan</a> that parses the project file to find strings (<a href="http://www.cocoanetics.com/2012/04/linguan-with-xib-support/">and soon XIB</a>) files. It simply cannot see them.</p>
<p>Here&#8217;s how it looks in the ShareKit project. If you ever see a x.bundle in a project you open, armed with the knowledge in this article, your reaction should be <em>&#8220;that&#8217;s bad&#8221;</em>.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-07.49.37.png"><img class="alignnone size-full wp-image-6308" title="ShareKit bundle" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-07.49.37.png" alt="" width="260" height="239" /></a></p>
<p>Of course the maintainers of these projects &#8220;have their reasons&#8221;. But I hope that by reading this you will agree with me that the reasons to not do it like this are better.</p>
<h3>Not Optimized</h3>
<p>Another issue is that this approach effectively disables the build time optimizations that Xcode carries out on the resources.</p>
<ul>
<li>strings files get converted into binary property lists</li>
<li>XIB files get compiled into binary NIBs</li>
<li>images get pngcrush-ed</li>
<li>and many other actions for which there are build rules set up</li>
</ul>
<p>That means resources that are simply bundled (by means of copying them together) are slower and not optimized for the mobile devices. You probably wouldn&#8217;t notice that for only a hand full of items, but if you have a large number of resources then these delays will add up slowing down your app. And even if that does not bother you very much then the engineer inside of you should cringe. It just feels so dirty&#8230;</p>
<h3>Not Updating</h3>
<p>Another reason for why it is a bad idea to hide files from Xcode is that it simply won&#8217;t know to rebuild your app if you make a change in one of the files hidden in such a bundle.</p>
<p>The Xcode build system has what is called dependencies. Implicit dependencies are source code files and resources that are part of certain targets. If such a dependence is modified then the incremental build process can determine which parts need to be re-compiled or re-optimized.</p>
<p>Say you change something in a single .m file. Xcode will not rebuild the entire app, but only create the .o for this updated file and then link it with the previously built (and unchanged .o files). Same with resources. Xcode only replaces resources in the output product .app bundle if it knows they where modified.</p>
<p>Resources in static bundles are invisible to Xcode and thus you always have to clean your build folder when doing a new build after changing them. Otherwise your updates will not propagate into your app.</p>
<h3>Enter the Resource Bundle Target</h3>
<p>Xcode, iOS and OS X have a mechanism to deal with folders that are looking like a single file but are actually containing multiple resources. This mechanism is modeled by the NSBundle class. You probably have worked with bundles before, namely the .app bundles that make up your app. Have you ever written [NSBundle mainBundle] before? I bet you did.</p>
<p>For NSBundle to be able to manage bundles it requires a special info.plist inside the bundle that contains some meta information, like an internal identifier. But once you have the bundle set up correctly you have multiple great options for getting at the files as I will show you below.</p>
<h3>How to Set Up a Resource Bundle Product</h3>
<p>A resource bundle is a product that we will set up a target for. It just so happens that my <a href="http://www.cocoanetics.com/parts/dtpinlockcontroller/">DTPinLockController</a> project is in need of some love, so it will serve as our example for this tutorial.</p>
<p>As a first step I needed to move the files into the modern way of structuring my projects. That is, for component projects I have a Core and a Demo folder at the project root. Then each has a Source and a Resources sub-folder. DTPinLockController has XIBs, Images and Localizable.strings files.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-08.22.31.png"><img class="alignnone size-full wp-image-6311" title="DTPinLockController Core tree" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-08.22.31.png" alt="" width="351" height="405" /></a></p>
<p>The source code goes into a Static Library target. All resources go into a Resource Bundle target. I&#8217;ve omitted the setup for the library here as we want to focus our attention on the resources.</p>
<p>Next we need to set up the Resource Bundle target. The template for this can be found in the OS X section, under &#8220;Framework &amp; Library&#8221;.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-08.36.15.png"><img class="alignnone  wp-image-6312" title="Bundle template" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-08.36.15.png" alt="" width="437" height="296" /></a></p>
<p>When removing the dynamic framework template Apple also removed the template for the Bundle. But with some minor modifications we can change the Mac bundle into one suitable for iOS. Since our bundle will not contain any executable code we don&#8217;t care about the settings for ARC and which foundation we want to use.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-08.39.12.png"><img class="alignnone  wp-image-6313" title="Creating the resource bundle target" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-08.39.12.png" alt="" width="437" height="296" /></a></p>
<p>I like to name the bundle product that same as my component so that in the end I have a DTPinLockController.bundle containing my resources and a libDTPinLockController.a library to go with it.</p>
<p>The template creates 3 files in DTPinLockController:</p>
<ul>
<li>an empty InfoPlist.strings file, we don&#8217;t need that</li>
<li>a DTPinLockController-Info.plist file, this is the META plist we need</li>
<li>a DTPinLockController-Prefix.pch file. No code in bundle means we can also remove that.</li>
</ul>
<p>I grab the plist and move it in to the root of my resources folder. The rest we can safely remove. I also rename it to Resources-Info.plist as to give an unsuspecting observer a hint that this is for the resource bundle.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-08.46.50.png"><img class="alignnone  wp-image-6314" title="The Resources Info.plist" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-08.46.50.png" alt="" width="583" height="203" /></a></p>
<p>We use this approach because the info plist for the resource bundle is too long to manually create. Note that there are several placeholders that get filled in during the build process, like the bundle name. All these settings come from the build settings which we are going to adjust next.</p>
<p>The default setting is to use the target name as name of products. I don&#8217;t like this because as I said about I want several products to be named DTPinLockController, but have the targets reflect their actual purpose.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-08.51.19.png"><img class="alignnone  wp-image-6315" title="Naming the targets" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-08.51.19.png" alt="" width="452" height="98" /></a></p>
<p>Because of this I end up with 3 targets with descriptive names like &#8220;Demo App&#8221;, &#8220;Static Library&#8221; and &#8220;Resource Bundle&#8221;. These have different product names &#8220;Demo&#8221;, &#8220;DTPinLockController&#8221; and &#8220;DTPinLockController&#8221; respectively. The different extensions and the prefix &#8220;lib&#8221; are automatically added by Xcode.</p>
<p>There are all the modifications we need to do on the build settings for the resource bundle:</p>
<ul>
<li>CMD-Backspace on the Base SDK to have it be the same as for the entire project: Latest iOS</li>
<li>Same on the &#8220;Mac OS X Deployment Target&#8221;</li>
<li>Same on the Architectures</li>
<li>Remove the reference to the PCH file</li>
<li>Remove &#8220;Installation Directory&#8221;</li>
<li>Set &#8220;Skip Install&#8221; to YES</li>
<li>Adjust &#8220;Info.plist File&#8221; to the correct path, e.g. Core/Resources/Resources-Info.plist</li>
</ul>
<p>The important part is the correct paths for the info plist and pch (none) and that Skip Install is YES because otherwise you get problems when trying to archive an app using the resource bundle. Since there is no code the compiler-related settings are really inconsequential, but I like to have them inherit from the project settings to have it look like a native iOS target.</p>
<p>In the build phases of the bundle target there is still a framework in &#8220;Link Binary with Libraries&#8221;. Remove this as well. It does not hurt as there is nothing to link it with, but might be confusing.</p>
<p>The final step for building the target is now to add the resources to it. You select the appropriate files in the project tree and set the checkmark in the right panel next to Resource Bundle.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-09.04.57.png"><img class="alignnone size-full wp-image-6316" title="Adding resources to the bundle" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-09.04.57.png" alt="" width="259" height="81" /></a></p>
<p>Xcode has added a scheme for the new target with the original name. So I remove all schemes and auto generate them from scratch. This will create one scheme per target and name them the same as the targets.</p>
<p>Then we can try and see if the bundle builds correctly.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-09.07.41.png"><img class="alignnone  wp-image-6317" title="Test-Build for the Resource Bundle" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-09.07.41.png" alt="" width="450" height="244" /></a></p>
<p>you can open up each build step and see that Xcode carried out the optimizations I alluded to above. In the case of this strings file you see &#8211;outputencoding binary that tells us that the strings file in the bundle will actually be binary.</p>
<p>You now have a DTPinLockController.bundle in the Products group that you can inspect to verify that this indeed is the case.</p>
<h3>Using the Resource Bundle</h3>
<p>There is a bug in Xcode 4.3.2 that might cause the list of resource to copy for the app target might get out of sync with the check marks in the project navigator. I had to manually go in the build phases of the demo app target and remove all the references to resources that are now part of the resource bundle.</p>
<p>Since the resource bundle is now a proper target we can add it as dependency to apps using it. This tells Xcode that if this dependency is somehow &#8220;dirty&#8221; then the app target is also in need of updating. So it will first build the dependent target and then include the product in the app build process.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-09.22.27.png"><img class="alignnone  wp-image-6318" title="Bildschirmfoto 2012-05-01 um 09.22.27" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-09.22.27.png" alt="" width="451" height="387" /></a></p>
<p>This shows the Static Library set up as dependency and in &#8220;Link Binary With Libraries&#8221;. Now we also want the bundle product to be in the &#8220;Copy Bundle Resources&#8221; phase. Click the Plus button and add the bundle product.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-09.27.57.png"><img class="alignnone size-full wp-image-6319" title="Bildschirmfoto 2012-05-01 um 09.27.57" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-05-01-um-09.27.57.png" alt="" width="403" height="465" /></a></p>
<p>This will make the bundle appear in the &#8220;Copy Bundle Resources&#8221;. If it wasn&#8217;t built before the app target then it will be built first, causing it to appear in the build products folder and from there it will be copied and included in the app product.</p>
<h3>A Few Code Changes</h3>
<p>If you reference images from a XIB and you put these images in the same resource bundle as the XIB then you don&#8217;t have to change anything. XIBs will load images from the same bundle that they were instantiated from.</p>
<p>However there are a couple of changes you need to make to your code so that the resources can be found at their new location.</p>
<h4>Strings</h4>
<p>The default macros for getting localized strings look for the strings files (aka &#8220;string tables&#8221;) in the main app bundle. These are the definitions of the 4 default macros and you can see that the bottom two have a way to specify the bundle to get the strings from whereas the first two hardcode the mainBundle.</p>

<div class="wp_codebox"><table><tr id="p630720"><td class="code" id="p6307code20"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#define NSLocalizedString(key, comment) \</span>
	    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/"><span style="color: #400080;">NSBundle</span></a> mainBundle<span style="color: #002200;">&#93;</span> localizedStringForKey<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>key<span style="color: #002200;">&#41;</span> value<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;&quot;</span> table<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>
<span style="color: #6e371a;">#define NSLocalizedStringFromTable(key, tbl, comment) \</span>
	    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/"><span style="color: #400080;">NSBundle</span></a> mainBundle<span style="color: #002200;">&#93;</span> localizedStringForKey<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>key<span style="color: #002200;">&#41;</span> value<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;&quot;</span> table<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>tbl<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>
<span style="color: #6e371a;">#define NSLocalizedStringFromTableInBundle(key, tbl, bundle, comment) \</span>
	    <span style="color: #002200;">&#91;</span>bundle localizedStringForKey<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>key<span style="color: #002200;">&#41;</span> value<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;&quot;</span> table<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>tbl<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>
<span style="color: #6e371a;">#define NSLocalizedStringWithDefaultValue(key, tbl, bundle, val, comment) \</span>
	    <span style="color: #002200;">&#91;</span>bundle localizedStringForKey<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>key<span style="color: #002200;">&#41;</span> value<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>val<span style="color: #002200;">&#41;</span> table<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>tbl<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span></pre></td></tr></table></div>

<p>You can create your own custom macro or category or what-have-you to have a shortcut, but to promote understanding here&#8217;s the entire code that we need to first get an NSBundle instance from our resource bundle and then get one string from it.</p>
<p>Note that specifying a table of nil means that the strings file is called &#8220;Localizable.strings&#8221;, for a table name of &#8220;Name&#8221; the file is called &#8220;Name.strings&#8221;</p>

<div class="wp_codebox"><table><tr id="p630721"><td class="code" id="p6307code21"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// get the resource bundle</span>
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>resourceBundlePath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/"><span style="color: #400080;">NSBundle</span></a> mainBundle<span style="color: #002200;">&#93;</span> pathForResource<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;DTPinLockController&quot;</span> ofType<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;bundle&quot;</span><span style="color: #002200;">&#93;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/"><span style="color: #400080;">NSBundle</span></a> <span style="color: #002200;">*</span>resourceBundle <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/"><span style="color: #400080;">NSBundle</span></a> bundleWithPath<span style="color: #002200;">:</span>resourceBundlePath<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// get a string</span>
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span><span style="color: #a61390;">string</span> <span style="color: #002200;">=</span> NSLocalizedStringFromTableInBundle<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Set Passcode&quot;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;DTPinLockController&quot;</span>, resourceBundle, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;PinLock&quot;</span><span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>We probably want to have a category on NSBundle specific to our project to load and cache in a static variable the resource bundle. And to go with that a localized string macro that hard codes this resource bundle. </p>
<h4>XIBs</h4>
<p>You probably have several places where you call [super initWithNibName:@"MyViewController" bundle:nil]. The nil in this case causes the NIB loader to assume that you mean the main bundle. Just as easily we can get the resource bundle and pass there here instead.</p>

<div class="wp_codebox"><table><tr id="p630722"><td class="code" id="p6307code22"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// get the resource bundle</span>
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>resourceBundlePath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/"><span style="color: #400080;">NSBundle</span></a> mainBundle<span style="color: #002200;">&#93;</span> pathForResource<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;DTPinLockController&quot;</span> ofType<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;bundle&quot;</span><span style="color: #002200;">&#93;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/"><span style="color: #400080;">NSBundle</span></a> <span style="color: #002200;">*</span>resourceBundle <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/"><span style="color: #400080;">NSBundle</span></a> bundleWithPath<span style="color: #002200;">:</span>resourceBundlePath<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// load View Controller from that</span>
UIViewController <span style="color: #002200;">*</span>vc <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>MyViewController alloc<span style="color: #002200;">&#93;</span> initWithNibName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;MyViewController&quot;</span> bundle<span style="color: #002200;">:</span>resourceBundle<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>Do we see a pattern here? You betcha! We always first get the NSBundle instance for the resource bundle and then pass this as a parameter to some method that does something with the resource.</p>
<h4>Images</h4>
<p>Ah, Graphics. With strings and XIBs both working the same way you would only be right to assume that there&#8217;s a imageNamed:inBundle: method, BUT&#8230; it is private. Radar <a href="http://openradar.appspot.com/10250430">rdar://10250430</a> by Cedric Luthi addresses this.</p>
<p>But fortunately for us we don&#8217;t really need this special method. The regular imageNamed can work with our resource bundles too! </p>
<p>All you need to do is prefix your image names with the name of the bundle, like this:</p>

<div class="wp_codebox"><table><tr id="p630723"><td class="code" id="p6307code23"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// load image from resource bundle</span>
UIImage <span style="color: #002200;">*</span>image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIImage imageNamed<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;DTPinLockController.bundle/Image.png&quot;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>This works because besides being a bundle object the resource bundle is also folder that can be traversed via its path.</p>
<p>The cool thing about loading XIBs, strings and images from resource bundles like this is that you retain the awesome powers of these methods. Like pathForResource:ofType: will automatically deliver the correct language version for the device if the resource is localized. Or imageNamed: will still automatically load Retina graphics where applicable or device-specific images with ~ipad or ~iphone.</p>
<p>I told you before that you don&#8217;t need to do anything special if these images are referenced from XIBs contained in the same resource bundle. So this is only necessary for the cases where you load the images from code.</p>
<h3>Conclusion</h3>
<p>This simplified tutorial has all targets and resource consumers in the same project. But the same concepts also work if you add the component project as a <a title="Sub-Projects in Xcode" href="http://www.cocoanetics.com/2011/12/sub-projects-in-xcode/">sub-project</a>.</p>
<p>I hope that I could convince you of the many advantages of resource bundles over static bundles. I&#8217;ve been successfully using them in almost all of my commercial components and many internal projects.</p>
<p>Bundle targets allow you to streamline the resource building process in a way that make larger projects way more effective and less error prone. Make it so!</p>
<p>&nbsp;</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=6307&amp;md5=5e9da4bb56b97811bc4eacd8e3c6a0af" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/05/resource-bundles/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F05%2Fresource-bundles%2F&amp;language=en_GB&amp;category=text&amp;title=Resource+Bundles&amp;description=When+shrink-wrapping+your+code+for+later+reuse+you+inadvertenly+will+come+into+the+situation+that+you+have+some+resources+%28strings%2C+XIBs%2C+images+et+al%29+in+your+project+that+you+also...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Creating a CoreData Model in Code</title>
		<link>http://www.cocoanetics.com/2012/04/creating-a-coredata-model-in-code/</link>
		<comments>http://www.cocoanetics.com/2012/04/creating-a-coredata-model-in-code/#comments</comments>
		<pubDate>Fri, 27 Apr 2012 13:40:27 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=6281</guid>
		<description><![CDATA[I&#8217;m working on my own file and image cache that uses CoreData for storage. The same way that NSURLCache is doing it, but with some optimizations that I know and understand. So I created DTDownloadCache and got it all working, but there was one minor thing that I didn&#8217;t like: The usual method of creating a CoreData entity model is by the entity editor built into Xcode. This meant that I had to include the .datamodeld file in apps using this. But I didn&#8217;t want to have to create a resource bundle just for this single file as you would have to do if you keep your reusable code in static libraries. Ugh! Fortunately there is a way how you can create a static model entirely in code so that you can make use of CoreData without having to ship an XML description of the model. &#160; First, lets have a quick look at how the model looked like in the editor. Plain and simple. The only special thing is to allow external storage for the fileData attribute. This allows CoreData to decide where to most efficiently store the file data. Small files will be stored in the entity itself. Large files get a GUID and will be saved in a subfolder of Library/Caches. If we wanted to support iOS 4 then we would have to create this mechanism ourselves which is available as of iOS 5. In XML this is represented as: The model is what CoreData needs to know how to translate between the SQLite database on disk and the managed objects in memory. Of course we could embed this model as a binary resource, but that would make out code unnecessarily more convoluted. I found a good example (Core Data Utility Tutorial) in the Apple documentation that explains the process. The method to create the same model as in the editor in code looks like this. ARC = On. - &#40;NSManagedObjectModel *&#41;_model &#123; NSManagedObjectModel *model = &#91;&#91;NSManagedObjectModel alloc&#93; init&#93;; &#160; // create the entity NSEntityDescription *entity = &#91;&#91;NSEntityDescription alloc&#93; init&#93;; &#91;entity setName:@&#34;DTCachedFile&#34;&#93;; &#91;entity setManagedObjectClassName:@&#34;DTCachedFile&#34;&#93;; &#160; // create the attributes NSMutableArray *properties = &#91;NSMutableArray array&#93;; &#160; NSAttributeDescription *remoteURLAttribute = &#91;&#91;NSAttributeDescription alloc&#93; init&#93;; &#91;remoteURLAttribute setName:@&#34;remoteURL&#34;&#93;; &#91;remoteURLAttribute setAttributeType:NSStringAttributeType&#93;; &#91;remoteURLAttribute setOptional:NO&#93;; &#91;remoteURLAttribute setIndexed:YES&#93;; &#91;properties addObject:remoteURLAttribute&#93;; &#160; NSAttributeDescription *fileDataAttribute = &#91;&#91;NSAttributeDescription alloc&#93; init&#93;; &#91;fileDataAttribute setName:@&#34;fileData&#34;&#93;; &#91;fileDataAttribute setAttributeType:NSBinaryDataAttributeType&#93;; &#91;fileDataAttribute setOptional:NO&#93;; &#91;fileDataAttribute setAllowsExternalBinaryDataStorage:YES&#93;; &#91;properties addObject:fileDataAttribute&#93;; &#160; NSAttributeDescription *lastAccessDateAttribute = &#91;&#91;NSAttributeDescription alloc&#93; init&#93;; &#91;lastAccessDateAttribute setName:@&#34;lastAccessDate&#34;&#93;; &#91;lastAccessDateAttribute setAttributeType:NSDateAttributeType&#93;; &#91;lastAccessDateAttribute setOptional:NO&#93;; &#91;properties addObject:lastAccessDateAttribute&#93;; &#160; NSAttributeDescription *expirationDateAttribute = &#91;&#91;NSAttributeDescription alloc&#93; init&#93;; &#91;expirationDateAttribute setName:@&#34;expirationDate&#34;&#93;; &#91;expirationDateAttribute setAttributeType:NSDateAttributeType&#93;; &#91;expirationDateAttribute setOptional:NO&#93;; &#91;properties addObject:expirationDateAttribute&#93;; &#160; NSAttributeDescription *contentTypeAttribute = &#91;&#91;NSAttributeDescription alloc&#93; init&#93;; &#91;contentTypeAttribute setName:@&#34;contentType&#34;&#93;; &#91;contentTypeAttribute setAttributeType:NSStringAttributeType&#93;; &#91;contentTypeAttribute setOptional:YES&#93;; &#91;properties addObject:contentTypeAttribute&#93;; &#160; NSAttributeDescription *fileSizeAttribute = &#91;&#91;NSAttributeDescription alloc&#93; init&#93;; &#91;fileSizeAttribute setName:@&#34;fileSize&#34;&#93;; &#91;fileSizeAttribute setAttributeType:NSInteger32AttributeType&#93;; &#91;fileSizeAttribute setOptional:NO&#93;; &#91;properties addObject:fileSizeAttribute&#93;; &#160; NSAttributeDescription *entityTagIdentifierAttribute = &#91;&#91;NSAttributeDescription alloc&#93; init&#93;; &#91;entityTagIdentifierAttribute setName:@&#34;entityTagIdentifier&#34;&#93;; &#91;entityTagIdentifierAttribute setAttributeType:NSStringAttributeType&#93;; &#91;entityTagIdentifierAttribute setOptional:YES&#93;; &#91;properties addObject:entityTagIdentifierAttribute&#93;; &#160; // add attributes to entity &#91;entity setProperties:properties&#93;; &#160; // add entity to model &#91;model setEntities:&#91;NSArray arrayWithObject:entity&#93;&#93;; &#160; return model; &#125; This looks more complicated than it really is because of the verbosity of Objective-C. The process is simply to create an empty model, create an entity, create the attributes, stir it all up and cook on medium flame for 15 minutes. If you compare this with the XML model above then you&#8217;ll see a couple of differences, but those are merely because I made my code model more strict, with less optional properties. The bare bones CoreData stack &#8211; consisting of the model, the persistent store coordinator and the managed object context might look like this: - &#40;void&#41;_setupCoreDataStack &#123; // setup managed object model &#160; /* NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@&#34;DTDownloadCache&#34; withExtension:@&#34;momd&#34;]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; */ &#160; // in code _managedObjectModel = &#91;self _model&#93;; &#160; // setup persistent store coordinator NSURL *storeURL = &#91;NSURL fileURLWithPath:&#91;&#91;NSString cachesPath&#93; stringByAppendingPathComponent:@&#34;DTDownload.cache&#34;&#93;&#93;; &#160; NSError *error = nil; _persistentStoreCoordinator = &#91;&#91;NSPersistentStoreCoordinator alloc&#93; initWithManagedObjectModel:_managedObjectModel&#93;; &#160; if &#40;!&#91;_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&#38;error&#93;&#41; &#123; // inconsistent model/store &#91;&#91;NSFileManager defaultManager&#93; removeItemAtURL:storeURL error:NULL&#93;; &#160; // retry once if &#40;!&#91;_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&#38;error&#93;&#41; &#123; NSLog&#40;@&#34;Unresolved error %@, %@&#34;, error, &#91;error userInfo&#93;&#41;; abort&#40;&#41;; &#125; &#125; &#160; // create MOC _managedObjectContext = &#91;&#91;NSManagedObjectContext alloc&#93; init&#93;; &#91;_managedObjectContext setPersistentStoreCoordinator:_persistentStoreCoordinator&#93;; &#125; Xcode turns the XML model into a momd file when building. The line that loads the model from this file is now commented out and instead the model is being constructed at runtime. You can modify the model until the first time it is used to access the persistent store. After that time it is read-only because changing it then would make it impossible for CoreData to talk to the data it has already saved. Also this approach does not bother with migrating models if something is changed. We simply remove the store file and retry adding the persistent store to the store coordinator. If that works then CoreData has created a fresh SQLite database [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/04/creating-a-coredata-model-in-code/"></g:plusone></div><p>I&#8217;m working on my own file and image cache that uses CoreData for storage. The same way that NSURLCache is doing it, but with some optimizations that I know and understand. So I created DTDownloadCache and got it all working, but there was one minor thing that I didn&#8217;t like: The usual method of creating a CoreData entity model is by the entity editor built into Xcode.</p>
<p>This meant that I had to include the .datamodeld file in apps using this. But I didn&#8217;t want to have to create a resource bundle just for this single file as you would have to do if you keep your reusable code in static libraries. Ugh!</p>
<p>Fortunately there is a way how you can create a static model entirely in code so that you can make use of CoreData without having to ship an XML description of the model.</p>
<p><span id="more-6281"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>First, lets have a quick look at how the model looked like in the editor.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-04-27-um-2.28.42-PM.png"><img class="alignnone size-full wp-image-6282" title="Model in Editor" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-04-27-um-2.28.42-PM.png" alt="" width="619" height="323" /></a></p>
<p>Plain and simple. The only special thing is to allow external storage for the fileData attribute. This allows CoreData to decide where to most efficiently store the file data. Small files will be stored in the entity itself. Large files get a GUID and will be saved in a subfolder of Library/Caches. If we wanted to support iOS 4 then we would have to create this mechanism ourselves which is available as of iOS 5.</p>
<p>In XML this is represented as:</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-04-27-um-3.04.25-PM.png"><img class="alignnone size-full wp-image-6287" title="CoreData XML model" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-04-27-um-3.04.25-PM.png" alt="" width="719" height="241" /></a></p>
<p>The model is what CoreData needs to know how to translate between the SQLite database on disk and the managed objects in memory. Of course we could embed this model <a title="Embedding Binary Resources" href="http://www.cocoanetics.com/2010/10/embedding-binary-resources/">as a binary resource</a>, but that would make out code unnecessarily more convoluted. I found a good example (<a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreDataUtilityTutorial/Articles/03_createModel.html">Core Data Utility Tutorial</a>) in the Apple documentation that explains the process.</p>
<p>The method to create the same model as in the editor in code looks like this. ARC = On.</p>

<div class="wp_codebox"><table><tr id="p628130"><td class="code" id="p6281code30"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectModel_Class/"><span style="color: #400080;">NSManagedObjectModel</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>_model
<span style="color: #002200;">&#123;</span>
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectModel_Class/"><span style="color: #400080;">NSManagedObjectModel</span></a> <span style="color: #002200;">*</span>model <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectModel_Class/"><span style="color: #400080;">NSManagedObjectModel</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// create the entity</span>
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSEntityDescription_Class/"><span style="color: #400080;">NSEntityDescription</span></a> <span style="color: #002200;">*</span>entity <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSEntityDescription_Class/"><span style="color: #400080;">NSEntityDescription</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>entity setName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;DTCachedFile&quot;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>entity setManagedObjectClassName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;DTCachedFile&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// create the attributes</span>
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/"><span style="color: #400080;">NSMutableArray</span></a> <span style="color: #002200;">*</span>properties <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/"><span style="color: #400080;">NSMutableArray</span></a> array<span style="color: #002200;">&#93;</span>;
&nbsp;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> <span style="color: #002200;">*</span>remoteURLAttribute <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>remoteURLAttribute setName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;remoteURL&quot;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>remoteURLAttribute setAttributeType<span style="color: #002200;">:</span>NSStringAttributeType<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>remoteURLAttribute setOptional<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>remoteURLAttribute setIndexed<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>properties addObject<span style="color: #002200;">:</span>remoteURLAttribute<span style="color: #002200;">&#93;</span>;
&nbsp;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> <span style="color: #002200;">*</span>fileDataAttribute <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>fileDataAttribute setName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;fileData&quot;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>fileDataAttribute setAttributeType<span style="color: #002200;">:</span>NSBinaryDataAttributeType<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>fileDataAttribute setOptional<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>fileDataAttribute setAllowsExternalBinaryDataStorage<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>properties addObject<span style="color: #002200;">:</span>fileDataAttribute<span style="color: #002200;">&#93;</span>;
&nbsp;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> <span style="color: #002200;">*</span>lastAccessDateAttribute <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>lastAccessDateAttribute setName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;lastAccessDate&quot;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>lastAccessDateAttribute setAttributeType<span style="color: #002200;">:</span>NSDateAttributeType<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>lastAccessDateAttribute setOptional<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>properties addObject<span style="color: #002200;">:</span>lastAccessDateAttribute<span style="color: #002200;">&#93;</span>;
&nbsp;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> <span style="color: #002200;">*</span>expirationDateAttribute <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>expirationDateAttribute setName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;expirationDate&quot;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>expirationDateAttribute setAttributeType<span style="color: #002200;">:</span>NSDateAttributeType<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>expirationDateAttribute setOptional<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>properties addObject<span style="color: #002200;">:</span>expirationDateAttribute<span style="color: #002200;">&#93;</span>;
&nbsp;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> <span style="color: #002200;">*</span>contentTypeAttribute <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>contentTypeAttribute setName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;contentType&quot;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>contentTypeAttribute setAttributeType<span style="color: #002200;">:</span>NSStringAttributeType<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>contentTypeAttribute setOptional<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>properties addObject<span style="color: #002200;">:</span>contentTypeAttribute<span style="color: #002200;">&#93;</span>;
&nbsp;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> <span style="color: #002200;">*</span>fileSizeAttribute <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>fileSizeAttribute setName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;fileSize&quot;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>fileSizeAttribute setAttributeType<span style="color: #002200;">:</span>NSInteger32AttributeType<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>fileSizeAttribute setOptional<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>properties addObject<span style="color: #002200;">:</span>fileSizeAttribute<span style="color: #002200;">&#93;</span>;
&nbsp;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> <span style="color: #002200;">*</span>entityTagIdentifierAttribute <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSAttributeDescription_Class/"><span style="color: #400080;">NSAttributeDescription</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>entityTagIdentifierAttribute setName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;entityTagIdentifier&quot;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>entityTagIdentifierAttribute setAttributeType<span style="color: #002200;">:</span>NSStringAttributeType<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>entityTagIdentifierAttribute setOptional<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>properties addObject<span style="color: #002200;">:</span>entityTagIdentifierAttribute<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// add attributes to entity</span>
	<span style="color: #002200;">&#91;</span>entity setProperties<span style="color: #002200;">:</span>properties<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// add entity to model</span>
	<span style="color: #002200;">&#91;</span>model setEntities<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> arrayWithObject<span style="color: #002200;">:</span>entity<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #a61390;">return</span> model;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This looks more complicated than it really is because of the verbosity of Objective-C. The process is simply to create an empty model, create an entity, create the attributes, stir it all up and cook on medium flame for 15 minutes. If you compare this with the XML model above then you&#8217;ll see a couple of differences, but those are merely because I made my code model more strict, with less optional properties.</p>
<p>The bare bones CoreData stack &#8211; consisting of the model, the persistent store coordinator and the managed object context might look like this:</p>

<div class="wp_codebox"><table><tr id="p628131"><td class="code" id="p6281code31"><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>_setupCoreDataStack
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// setup managed object model</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">/*
	NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@&quot;DTDownloadCache&quot; withExtension:@&quot;momd&quot;];
	_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
	 */</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// in code</span>
	_managedObjectModel <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self _model<span style="color: #002200;">&#93;</span>; 
&nbsp;
	<span style="color: #11740a; font-style: italic;">// setup persistent store coordinator</span>
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/"><span style="color: #400080;">NSURL</span></a> <span style="color: #002200;">*</span>storeURL <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/"><span style="color: #400080;">NSURL</span></a> fileURLWithPath<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> cachesPath<span style="color: #002200;">&#93;</span> stringByAppendingPathComponent<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;DTDownload.cache&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/"><span style="color: #400080;">NSError</span></a> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
	_persistentStoreCoordinator <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSPersistentStoreCoordinator_Class/"><span style="color: #400080;">NSPersistentStoreCoordinator</span></a> alloc<span style="color: #002200;">&#93;</span> initWithManagedObjectModel<span style="color: #002200;">:</span>_managedObjectModel<span style="color: #002200;">&#93;</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>_persistentStoreCoordinator addPersistentStoreWithType<span style="color: #002200;">:</span>NSSQLiteStoreType configuration<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> URL<span style="color: #002200;">:</span>storeURL options<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> error<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>
		<span style="color: #11740a; font-style: italic;">// inconsistent model/store</span>
		<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/"><span style="color: #400080;">NSFileManager</span></a> defaultManager<span style="color: #002200;">&#93;</span> removeItemAtURL<span style="color: #002200;">:</span>storeURL error<span style="color: #002200;">:</span><span style="color: #a61390;">NULL</span><span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #11740a; font-style: italic;">// retry once</span>
		<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>_persistentStoreCoordinator addPersistentStoreWithType<span style="color: #002200;">:</span>NSSQLiteStoreType configuration<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> URL<span style="color: #002200;">:</span>storeURL options<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> error<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;Unresolved error %@, %@&quot;</span>, error, <span style="color: #002200;">&#91;</span>error userInfo<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
			<a href="http://www.opengroup.org/onlinepubs/009695399/functions/abort.html"><span style="color: #a61390;">abort</span></a><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
		<span style="color: #002200;">&#125;</span>
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// create MOC</span>
	_managedObjectContext <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/"><span style="color: #400080;">NSManagedObjectContext</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>_managedObjectContext setPersistentStoreCoordinator<span style="color: #002200;">:</span>_persistentStoreCoordinator<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Xcode turns the XML model into a momd file when building. The line that loads the model from this file is now commented out and instead the model is being constructed at runtime. </p>
<p>You can modify the model until the first time it is used to access the persistent store. After that time it is read-only because changing it then would make it impossible for CoreData to talk to the data it has already saved.</p>
<p>Also this approach does not bother with migrating models if something is changed. We simply remove the store file and retry adding the persistent store to the store coordinator. If that works then CoreData has created a fresh SQLite database on disk that fits our new model.</p>
<h3>Conclusion</h3>
<p>CoreData is powerful to be used for maintaining the META information of caches and with the above approach you can easily keep your custom caches in static libraries without the need of adding a clunky model file to apps that are linking in this lib.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=6281&amp;md5=1ec05d6a7dd1bb8c8ba1a5fe5f36edaf" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/04/creating-a-coredata-model-in-code/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F04%2Fcreating-a-coredata-model-in-code%2F&amp;language=en_GB&amp;category=text&amp;title=Creating+a+CoreData+Model+in+Code&amp;description=I%26%238217%3Bm+working+on+my+own+file+and+image+cache+that+uses+CoreData+for+storage.+The+same+way+that+NSURLCache+is+doing+it%2C+but+with+some+optimizations+that+I+know+and...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Disabling Facebook SSO, elegantly</title>
		<link>http://www.cocoanetics.com/2012/04/disabling-facebook-sso-elegantly/</link>
		<comments>http://www.cocoanetics.com/2012/04/disabling-facebook-sso-elegantly/#comments</comments>
		<pubDate>Wed, 25 Apr 2012 11:40:15 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=6271</guid>
		<description><![CDATA[The experts are still out as to the motivations behind Facebook&#8217;s iOS SDK strategy. But it is rather clear that if Facebook has their way then everybody is to be using their Single Sign-On (SSO) technique. Besides all potential advantages of having this SSO in place it has to leave your app for signing on. Not exactly something that is useful for all use cases. We have one case (involving ShareKit) which works better with the old style of signing into Facebook. This &#8220;traditional approach&#8221; shows the login dialog in a web pop up instead of leaving the app. In this post I&#8217;m sharing the 3 methods how to hack the Facebook class and bend it to our will. &#160; When researching for a way to disable SSO and restore the &#8220;old style&#8221; you inadvertently come across several people telling you to simply hack the authorize: method in Facebook.m. Original Code Hack The code for it is Open Source and so that poses little problem for a simple modification. You simply replace the method with the version below: - &#40;void&#41;authorize:&#40;NSArray *&#41;permissions &#123; &#91;self setValue:permissions forKey:@&#34;permissions&#34;&#93;; &#160; &#91;self authorizeWithFBAppAuth:NO safariAuth:NO&#93;; &#125; But unfortunately that means you&#8217;ll have to modify code that is owned by somebody else. And I&#8217;m not talking about licensing concerns but the simple fact that if Facebook updates the SDK you have to do this change every time after updating to the latest version. I am using the Facebook SDK via a submodule in ShareKit and I generally want to avoid having to keep track of modifications in third-party code. Which brings us to method number 2. Category Hack We know that we can add methods to existing classes by simply adding them in categories. If you have a method that has the same name as an existing method then the new method simply replaces the old one. So we can wrap the above hack in a category like so: Facebook+NoSSO.h #import &#34;Facebook.h&#34; &#160; @interface Facebook &#40;NoSSO&#41; &#160; - &#40;void&#41;authorize:&#40;NSArray *&#41;permissions; &#160; @end Facebook+NoSSO.m #import &#34;Facebook+NoSSO.h&#34; &#160; #import &#34;Facebook.h&#34; &#160; @interface Facebook &#40;&#41; &#160; - &#40;void&#41;authorizeWithFBAppAuth:&#40;BOOL&#41;tryFBAppAuth safariAuth:&#40;BOOL&#41;trySafariAuth; @end &#160; @implementation Facebook &#40;NoSSO&#41; &#160; - &#40;void&#41;authorize:&#40;NSArray *&#41;permissions &#123; &#91;self setValue:permissions forKey:@&#34;permissions&#34;&#93;; &#160; &#91;self authorizeWithFBAppAuth:NO safariAuth:NO&#93;; &#125; &#160; @end Notice that we need to define the authorizeWithFBAppAuth:safariAuth: in an anonymous category so that the compiler accepts us calling it from our own authorize: method. Without that we would get a compiler warning. This method is internal to the Facebook class and not exposed via the header. This method has two problems: 1) I don&#8217;t think that Apple actually guarantees a certain order in which classes and categories are loaded. So this is a bit risky to rely on it having always been working. 2) As of Xcode 4.3.2 the compiler will actually warn you &#8220;Category is implementing a method which will also be implemented by its primary class&#8221; Which brings us to the third &#8211; most elegant method. Swizzeling Hack Being dynamic in nature the Objective-C runtime allows us to dynamically changes classes and methods which our app is running. One such technique is called &#8220;Method Swizzeling&#8221; which basically means to exchange two methods. With this method you can substitute your own method implantation. First I borrowed some code from ShareKit and adapted it for general use in DTFoundation: NSObject+DTRuntime.h @interface NSObject &#40;DTRuntime&#41; &#160; + &#40;void&#41;swizzleMethod:&#40;SEL&#41;selector withMethod:&#40;SEL&#41;otherSelector; &#160; @end NSObject+DTRuntime.m #import &#60;objc/runtime.h&#62; &#160; @implementation NSObject &#40;DTRuntime&#41; &#160; + &#40;void&#41;swizzleMethod:&#40;SEL&#41;selector withMethod:&#40;SEL&#41;otherSelector &#123; // my own class is being targetted Class c = &#91;self class&#93;; &#160; // get the methods from the selectors Method originalMethod = class_getInstanceMethod&#40;c, selector&#41;; Method otherMethod = class_getInstanceMethod&#40;c, otherSelector&#41;; &#160; if &#40;class_addMethod&#40;c, selector, method_getImplementation&#40;otherMethod&#41;, method_getTypeEncoding&#40;otherMethod&#41;&#41;&#41; &#123; class_replaceMethod&#40;c, otherSelector, method_getImplementation&#40;originalMethod&#41;, method_getTypeEncoding&#40;originalMethod&#41;&#41;; &#125; else &#123; method_exchangeImplementations&#40;originalMethod, otherMethod&#41;; &#125; &#125; &#160; @end That takes care of the actual exchanging. I have to admit that I don&#8217;t quite understand the if, because in my tests it always ended up in the method_exchangeImplementations part. But as long as it is working&#8230; Now we have to only have a method with a unique name (to avoid the warning) and then we can exchange this method for the original authorize: method by means of this swizzle. The modified category now looks like this: Facebook+NoSSO.h #import &#34;Facebook.h&#34; &#160; @interface Facebook &#40;iCatalog&#41; &#160; - &#40;void&#41;authorize_noSSO:&#40;NSArray *&#41;permissions; &#160; + &#40;void&#41;toggleSingleSignOn; &#160; @end Facebook+NoSSO.m #import &#34;Facebook+iCatalog.h&#34; #import &#34;NSObject+DTRuntime.h&#34; &#160; @interface Facebook &#40;&#41; &#160; - &#40;void&#41;authorizeWithFBAppAuth:&#40;BOOL&#41;tryFBAppAuth safariAuth:&#40;BOOL&#41;trySafariAuth; @end &#160; @implementation Facebook &#40;iCatalog&#41; &#160; - &#40;void&#41;authorize_noSSO:&#40;NSArray *&#41;permissions &#123; &#91;self setValue:permissions forKey:@&#34;permissions&#34;&#93;; &#160; &#91;self authorizeWithFBAppAuth:NO safariAuth:NO&#93;; &#125; &#160; + &#40;void&#41;toggleSingleSignOn &#123; &#91;Facebook swizzleMethod:@selector&#40;authorize:&#41; withMethod:@selector&#40;authorize_noSSO:&#41;&#93;; &#125; &#160; @end You see that I have also added a class method to toggle SSO on and off. I named it &#8220;toggle&#8221; because each call will exchange the two method implementations. While the first toggle will disable SSO the second call restores the original method and thus [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/04/disabling-facebook-sso-elegantly/"></g:plusone></div><p>The experts are still out as to the motivations behind Facebook&#8217;s iOS SDK strategy. But it is rather clear that if Facebook has their way then everybody is to be using their Single Sign-On (SSO) technique. Besides all potential advantages of having this SSO in place it has to leave your app for signing on. </p>
<p>Not exactly something that is useful for all use cases. We have one case (involving ShareKit) which works better with the old style of signing into Facebook. This &#8220;traditional approach&#8221; shows the login dialog in a web pop up instead of leaving the app. </p>
<p>In this post I&#8217;m sharing the 3 methods how to hack the Facebook class and bend it to our will.</p>
<p><span id="more-6271"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>When researching for a way to disable SSO and restore the &#8220;old style&#8221; you inadvertently come across several people telling you to simply hack the authorize: method in Facebook.m. </p>
<h3>Original Code Hack</h3>
<p>The code for it is <a href="https://github.com/facebook/facebook-ios-sdk">Open Source</a> and so that poses little problem for a simple modification. You simply replace the method with the version below:</p>

<div class="wp_codebox"><table><tr id="p627142"><td class="code" id="p6271code42"><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>authorize<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>permissions 
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>self setValue<span style="color: #002200;">:</span>permissions forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;permissions&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>self authorizeWithFBAppAuth<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span> safariAuth<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>But unfortunately that means you&#8217;ll have to modify code that is owned by somebody else. And I&#8217;m not talking about licensing concerns but the simple fact that if Facebook updates the SDK you have to do this change every time after updating to the latest version. </p>
<p>I am using the Facebook SDK via a submodule in ShareKit and I generally want to avoid having to keep track of modifications in third-party code. Which brings us to method number 2.</p>
<h3>Category Hack</h3>
<p>We know that we can add methods to existing classes by simply adding them in categories. If you have a method that has the same name as an existing method then the new method simply replaces the old one. So we can wrap the above hack in a category like so:</p>
<p><strong>Facebook+NoSSO.h</strong></p>

<div class="wp_codebox"><table><tr id="p627143"><td class="code" id="p6271code43"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;Facebook.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> Facebook <span style="color: #002200;">&#40;</span>NoSSO<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>authorize<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>permissions;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p><strong>Facebook+NoSSO.m</strong></p>

<div class="wp_codebox"><table><tr id="p627144"><td class="code" id="p6271code44"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;Facebook+NoSSO.h&quot;</span>
&nbsp;
<span style="color: #6e371a;">#import &quot;Facebook.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> Facebook <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>authorizeWithFBAppAuth<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>tryFBAppAuth
                    safariAuth<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>trySafariAuth;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> Facebook <span style="color: #002200;">&#40;</span>NoSSO<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>authorize<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>permissions 
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>self setValue<span style="color: #002200;">:</span>permissions forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;permissions&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>self authorizeWithFBAppAuth<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span> safariAuth<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>Notice that we need to define the authorizeWithFBAppAuth:safariAuth: in an anonymous category so that the compiler accepts us calling it from our own authorize: method. Without that we would get a compiler warning. This method is internal to the Facebook class and not exposed via the header.</p>
<p>This method has two problems: 1) I don&#8217;t think that Apple actually guarantees a certain order in which classes and categories are loaded. So this is a bit risky to rely on it having always been working. 2) As of Xcode 4.3.2 the compiler will actually warn you <em>&#8220;Category is implementing a method which will also be implemented by its primary class&#8221;</em> </p>
<p>Which brings us to the third &#8211; most elegant method.</p>
<h3>Swizzeling Hack</h3>
<p>Being dynamic in nature the Objective-C runtime allows us to dynamically changes classes and methods which our app is running. One such technique is called &#8220;Method Swizzeling&#8221; which basically means to exchange two methods. With this method you can substitute your own method implantation.</p>
<p>First I borrowed some code from ShareKit and adapted it for general use in DTFoundation:</p>
<p><strong>NSObject+DTRuntime.h</strong></p>

<div class="wp_codebox"><table><tr id="p627145"><td class="code" id="p6271code45"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/"><span style="color: #400080;">NSObject</span></a> <span style="color: #002200;">&#40;</span>DTRuntime<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>swizzleMethod<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">SEL</span><span style="color: #002200;">&#41;</span>selector withMethod<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">SEL</span><span style="color: #002200;">&#41;</span>otherSelector;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p><strong>NSObject+DTRuntime.m</strong></p>

<div class="wp_codebox"><table><tr id="p627146"><td class="code" id="p6271code46"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &lt;objc/runtime.h&gt;</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/"><span style="color: #400080;">NSObject</span></a> <span style="color: #002200;">&#40;</span>DTRuntime<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>swizzleMethod<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">SEL</span><span style="color: #002200;">&#41;</span>selector withMethod<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">SEL</span><span style="color: #002200;">&#41;</span>otherSelector
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// my own class is being targetted</span>
	<span style="color: #a61390;">Class</span> c <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self class<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// get the methods from the selectors</span>
	Method originalMethod <span style="color: #002200;">=</span> class_getInstanceMethod<span style="color: #002200;">&#40;</span>c, selector<span style="color: #002200;">&#41;</span>;
	Method otherMethod <span style="color: #002200;">=</span> class_getInstanceMethod<span style="color: #002200;">&#40;</span>c, otherSelector<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>class_addMethod<span style="color: #002200;">&#40;</span>c, selector, method_getImplementation<span style="color: #002200;">&#40;</span>otherMethod<span style="color: #002200;">&#41;</span>, method_getTypeEncoding<span style="color: #002200;">&#40;</span>otherMethod<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		class_replaceMethod<span style="color: #002200;">&#40;</span>c, otherSelector, method_getImplementation<span style="color: #002200;">&#40;</span>originalMethod<span style="color: #002200;">&#41;</span>, method_getTypeEncoding<span style="color: #002200;">&#40;</span>originalMethod<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">else</span>
	<span style="color: #002200;">&#123;</span>
		method_exchangeImplementations<span style="color: #002200;">&#40;</span>originalMethod, otherMethod<span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>That takes care of the actual exchanging. I have to admit that I don&#8217;t quite understand the if, because in my tests it always ended up in the method_exchangeImplementations part. But as long as it is working&#8230; <img src='http://www.cocoanetics.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Now we have to only have a method with a unique name (to avoid the warning) and then we can exchange this method for the original authorize: method by means of this swizzle. The modified category now looks like this:</p>
<p><strong>Facebook+NoSSO.h</strong></p>

<div class="wp_codebox"><table><tr id="p627147"><td class="code" id="p6271code47"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;Facebook.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> Facebook <span style="color: #002200;">&#40;</span>iCatalog<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>authorize_noSSO<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>permissions;
&nbsp;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>toggleSingleSignOn;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p><strong>Facebook+NoSSO.m</strong></p>

<div class="wp_codebox"><table><tr id="p627148"><td class="code" id="p6271code48"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;Facebook+iCatalog.h&quot;</span>
<span style="color: #6e371a;">#import &quot;NSObject+DTRuntime.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> Facebook <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>authorizeWithFBAppAuth<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>tryFBAppAuth
                    safariAuth<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>trySafariAuth;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> Facebook <span style="color: #002200;">&#40;</span>iCatalog<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>authorize_noSSO<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>permissions 
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>self setValue<span style="color: #002200;">:</span>permissions forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;permissions&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>self authorizeWithFBAppAuth<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span> safariAuth<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>toggleSingleSignOn
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>Facebook swizzleMethod<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>authorize<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span> withMethod<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>authorize_noSSO<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>You see that I have also added a class method to toggle SSO on and off. I named it &#8220;toggle&#8221; because each call will exchange the two method implementations. While the first toggle will disable SSO the second call restores the original method and thus re-enables it.</p>
<p>With this you only have to call the toggleSingleSignOn once per app launch, the best place is the app delegate&#8217;s +initialize which is guaranteed to be called just once and also in a thread-safe manner.</p>

<div class="wp_codebox"><table><tr id="p627149"><td class="code" id="p6271code49"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> MyAppDelegate
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>initialize
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// disable Facebook SSO</span>
	<span style="color: #002200;">&#91;</span>Facebook toggleSingleSignOn<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>That&#8217;s all it takes. </p>
<h3>Conclusion</h3>
<p>Of the three ways how you can modify somebody else&#8217;s code&#8217;s behavior the one that actually replaces the implementation via swizzeling is the most convenient and least dangerous, at least if you know what you are doing.</p>
<p>This alternative does not have the drawback of original code hacking that you incur an additional maintenance overhead. And it does not have the drawback of compiler warnings for the category hack approach.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=6271&amp;md5=939d9a1be0be870d11af3c9ccc9faee2" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/04/disabling-facebook-sso-elegantly/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F04%2Fdisabling-facebook-sso-elegantly%2F&amp;language=en_GB&amp;category=text&amp;title=Disabling+Facebook+SSO%2C+elegantly&amp;description=The+experts+are+still+out+as+to+the+motivations+behind+Facebook%26%238217%3Bs+iOS+SDK+strategy.+But+it+is+rather+clear+that+if+Facebook+has+their+way+then+everybody+is+to+be...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Containing ViewControllers</title>
		<link>http://www.cocoanetics.com/2012/04/containing-viewcontrollers/</link>
		<comments>http://www.cocoanetics.com/2012/04/containing-viewcontrollers/#comments</comments>
		<pubDate>Sat, 14 Apr 2012 13:44:59 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=6225</guid>
		<description><![CDATA[For a project that I am currently working on I needed to implement a custom container view controller. I was feeling my way forward in the dark for the most part because this does not seem to be a widely used technique. Developers &#8211; understandably &#8211; favor reusing and skinning existing view controllers over creating new containers. However there are some scenarios where you should prefer to make your own container because it greatly simplifies your code over trying to bend a UINavigationController or UITabBarController to your will. Do you remember the times when those two where the only two containers available? I distinctly remember using a UINavigationController with hidden nav bar as a view controller to contain multiple full views. And you probably had do do your own view juggling and animations because for the most part the standard transitions would be useless. Fortunately we can no file this as a fond memory of the past and move on to implementing our own containers. &#160; The first thing to wrap your head around is the notion that besides a hierarchy of views you now also have to have a consistent hierarchy of view controllers. Before iOS 5 people would often create a new view controller and then slap this VC&#8217;s view into an existing view hierarchy. Now more! Nowadays you never would resort to this. Instead you use the mechanisms afforded by UIViewController to add and remove child view controllers. Another notion is that we&#8217;ve trained ourselves to think of view controllers as being responsible for one entire full screen, think of the sub view controllers of a tab bar controller. But ever since UISplitViewController which arrived with the iPad this is no longer the true mantra. Viewcontrollers are supposed to manage a coherent region on the screen, that can be the entire screen for lack of space on an iPhone, but it can also be a content bar at one of the sides of the screen. Like UISplitViewController which has two sub-viewcontrollers, one for the left (&#8220;master&#8221;) panel and one for the right (&#8220;detail&#8221;) panel. UIViewController provides two methods to add a view controller as a child and to remove it later. Those are part of the &#8220;UIContainerViewControllerProtectedMethods&#8221; category extension for UIViewController: @interface UIViewController &#40;UIContainerViewControllerProtectedMethods&#41; &#160; - &#40;void&#41;addChildViewController:&#40;UIViewController *&#41;childController; - &#40;void&#41;removeFromParentViewController; &#160; @end These two methods do exactly what their names suggest. Though what&#8217;s not quite obvious is how you are supposed to use them. And if and how you should combine these with addSubview and removeFromSuperview. Hence this exploration. Note: All this assumes we use ARC. According to the docs it is up to us to define the kinds of relationships we want to model. Be it only a single VC visible at the time like nav controllers, or multiple that can be reached through tabs. Or even multiple VCs that are sort of like pages. There are three possible things that you want to be able to do with your sub-viewcontrollers that have slightly different semantics: Add it to your container Remove it from your container Transition to another view controller (i.e. add the new and remove the old) For any of these you also want to be be assured that the 4 view delegate methods get properly called, as well as the new 2 delegate methods that fire before and after a VC moved to a new parent. Note that a parent of nil means that it was removed. Why is this attention to the delegate messaging necessary? You probably use the view(Did&#124;Will)(A&#124;Disa)pear methods to do some last setup or teardown and so you are interested that they get properly called. And also there is an ugly warning in the console about unbalanced messages if you get something wrong here. We&#8217;ll dive into greater detail with a sample. Let&#8217;s say we want to get an effect similar to a tabbed view controller. i.e. we have an array of view controllers and we want to switch between these. Since this container VC will be our app&#8217;s root view controller we want to show the first sub-VC when it shows. Basic Setup Let&#8217;s put the necessary bare bones IVARs in the implementation because we only need to have access to these inside our own ContainerViewController. @implementation ContainerViewController &#123; NSArray *_subViewControllers; UIViewController *_selectedViewController; UIView *_containerView; &#125; The subVCs will be a static array of view controllers that the developer can set. The selected VC will hold a reference to the currently showing VC and the container view will be the area where we want our sub VC&#8217;s view to be positioned. Let&#8217;s start by setting up the container view in the container&#8217;s loadView: - &#40;void&#41;loadView &#123; // set up the base view CGRect frame = &#91;&#91;UIScreen mainScreen&#93; applicationFrame&#93;; UIView *view = &#91;&#91;UIView alloc&#93; initWithFrame:frame&#93;; view.autoresizingMask = UIViewAutoresizingFlexibleWidth &#124; [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/04/containing-viewcontrollers/"></g:plusone></div><p>For a project that I am currently working on I needed to implement a custom container view controller. I was feeling my way forward in the dark for the most part because this does not seem to be a widely used technique. Developers &#8211; understandably &#8211; favor reusing and skinning existing view controllers over creating new containers.</p>
<p>However there are some scenarios where you should prefer to make your own container because it greatly simplifies your code over trying to bend a UINavigationController or UITabBarController to your will. Do you remember the times when those two where the only two containers available?</p>
<p>I distinctly remember using a UINavigationController with hidden nav bar as a view controller to contain multiple full views. And you probably had do do your own view juggling and animations because for the most part the standard transitions would be useless. Fortunately we can no file this as a fond memory of the past and move on to implementing our own containers.</p>
<p><span id="more-6225"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>The first thing to wrap your head around is the notion that besides a hierarchy of views you now also have to have a consistent hierarchy of view controllers. Before iOS 5 people would often create a new view controller and then slap this VC&#8217;s view into an existing view hierarchy. Now more!</p>
<p>Nowadays you never would resort to this. Instead you use the mechanisms afforded by UIViewController to add and remove child view controllers.</p>
<p>Another notion is that we&#8217;ve trained ourselves to think of view controllers as being responsible for one entire full screen, think of the sub view controllers of a tab bar controller. But ever since UISplitViewController which arrived with the iPad this is no longer the true mantra. Viewcontrollers are supposed to manage a coherent region on the screen, that can be the entire screen for lack of space on an iPhone, but it can also be a content bar at one of the sides of the screen. Like UISplitViewController which has two sub-viewcontrollers, one for the left (&#8220;master&#8221;) panel and one for the right (&#8220;detail&#8221;) panel.</p>
<p>UIViewController provides two methods to add a view controller as a child and to remove it later. Those are part of the &#8220;UIContainerViewControllerProtectedMethods&#8221; category extension for UIViewController:</p>

<div class="wp_codebox"><table><tr id="p622569"><td class="code" id="p6225code69"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> UIViewController <span style="color: #002200;">&#40;</span>UIContainerViewControllerProtectedMethods<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>addChildViewController<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIViewController <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>childController;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>removeFromParentViewController;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>These two methods do exactly what their names suggest. Though what&#8217;s not quite obvious is how you are supposed to use them. And if and how you should combine these with addSubview and removeFromSuperview. Hence this exploration. Note: All this assumes we use ARC.</p>
<p>According to the docs it is up to us to define the kinds of relationships we want to model. Be it only a single VC visible at the time like nav controllers, or multiple that can be reached through tabs. Or even multiple VCs that are sort of like pages. </p>
<p>There are three possible things that you want to be able to do with your sub-viewcontrollers that have slightly different semantics:</p>
<ul>
<li><strong>Add</strong> it to your container</li>
<li><strong>Remove</strong> it from your container</li>
<li><strong>Transition</strong> to another view controller (i.e. add the new and remove the old)</li>
</ul>
<p>For any of these you also want to be be assured that the 4 view delegate methods get properly called, as well as the new 2 delegate methods that fire before and after a VC moved to a new parent. Note that a parent of nil means that it was removed.</p>
<p>Why is this attention to the delegate messaging necessary? You probably use the view(Did|Will)(A|Disa)pear methods to do some last setup or teardown and so you are interested that they get properly called. And also there is an ugly warning in the console about unbalanced messages if you get something wrong here.</p>
<p>We&#8217;ll dive into greater detail with a sample. Let&#8217;s say we want to get an effect similar to a tabbed view controller. i.e. we have an array of view controllers and we want to switch between these. Since this container VC will be our app&#8217;s root view controller we want to show the first sub-VC when it shows.</p>
<h3>Basic Setup</h3>
<p>Let&#8217;s put the necessary bare bones IVARs in the implementation because we only need to have access to these inside our own ContainerViewController.</p>

<div class="wp_codebox"><table><tr id="p622570"><td class="code" id="p6225code70"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> ContainerViewController
<span style="color: #002200;">&#123;</span>
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span>_subViewControllers;
	UIViewController <span style="color: #002200;">*</span>_selectedViewController;
	UIView <span style="color: #002200;">*</span>_containerView;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>The subVCs will be a static array of view controllers that the developer can set. The selected VC will hold a reference to the currently showing VC and the container view will be the area where we want our sub VC&#8217;s view to be positioned. Let&#8217;s start by setting up the container view in the container&#8217;s loadView:</p>

<div class="wp_codebox"><table><tr id="p622571"><td class="code" id="p6225code71"><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>loadView
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// set up the base view</span>
	CGRect frame <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIScreen mainScreen<span style="color: #002200;">&#93;</span> applicationFrame<span style="color: #002200;">&#93;</span>;
	UIView <span style="color: #002200;">*</span>view <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIView alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span>frame<span style="color: #002200;">&#93;</span>;
	view.autoresizingMask <span style="color: #002200;">=</span> UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	view.backgroundColor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIColor blueColor<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// set up content view a bit inset</span>
	frame <span style="color: #002200;">=</span> CGRectInset<span style="color: #002200;">&#40;</span>view.bounds, <span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">100</span><span style="color: #002200;">&#41;</span>;
	_containerView <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIView alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span>frame<span style="color: #002200;">&#93;</span>;
	_containerView.backgroundColor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIColor redColor<span style="color: #002200;">&#93;</span>;
	_containerView.autoresizingMask <span style="color: #002200;">=</span> UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	<span style="color: #002200;">&#91;</span>view addSubview<span style="color: #002200;">:</span>_containerView<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// from here on the container is automatically adjusting to the orientation</span>
	self.view <span style="color: #002200;">=</span> view;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>I&#8217;ve colored the main view blue and the container view red for clarity. The sub-VCs will go in the red area and be automatically resized if we rotate the device.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-04-14-um-2.10.24-PM.png"><img src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-04-14-um-2.10.24-PM-232x300.png" alt="" title="Basic Setup of Container" width="232" height="300" class="alignnone size-medium wp-image-6226" /></a></p>
<p>The integration in the app delegate is a mere formality, add the import for the header, allocate an instance and set it as root VC.</p>

<div class="wp_codebox"><table><tr id="p622572"><td class="code" id="p6225code72"><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>application<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIApplication <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>application didFinishLaunchingWithOptions<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/"><span style="color: #400080;">NSDictionary</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>launchOptions
<span style="color: #002200;">&#123;</span>
    self.window <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIWindow alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIScreen mainScreen<span style="color: #002200;">&#93;</span> bounds<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	ContainerViewController <span style="color: #002200;">*</span>container <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>ContainerViewController alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;	
 	self.window.rootViewController <span style="color: #002200;">=</span> container;
&nbsp;
    <span style="color: #002200;">&#91;</span>self.window makeKeyAndVisible<span style="color: #002200;">&#93;</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>Next we need a couple of view controllers to play the role of the sub-VCs. Let&#8217;s create a simple UIViewController subclass that has a UILabel as it&#8217;s main view, so that we can display something there to tell them apart. Do avoid overcomplicating things for this example we simple take the view&#8217;s own description in there. This way we see if the display changes.</p>

<div class="wp_codebox"><table><tr id="p622573"><td class="code" id="p6225code73"><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>loadView
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// set up the base view</span>
	CGRect frame <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIScreen mainScreen<span style="color: #002200;">&#93;</span> applicationFrame<span style="color: #002200;">&#93;</span>;
	UILabel <span style="color: #002200;">*</span>label <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UILabel alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span>frame<span style="color: #002200;">&#93;</span>;
	label.numberOfLines <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>; <span style="color: #11740a; font-style: italic;">// multiline</span>
	label.textAlignment <span style="color: #002200;">=</span> UITextAlignmentCenter;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// let's just have this view description</span>
	label.text <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self description<span style="color: #002200;">&#93;</span>;
	self.view <span style="color: #002200;">=</span> label;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>I bet you never before had a view controller which consisted only of a UILabel. For Science! <img src='http://www.cocoanetics.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<h3>Adding</h3>
<p>Next we need to put a couple of these PageViewControllers into an array and have a method that allows us to set this array into our container. Let&#8217;s assume that you know how to create a property for the subViewControllers. In the app delegate we have these additional lines:</p>

<div class="wp_codebox"><table><tr id="p622574"><td class="code" id="p6225code74"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// make an array of 5 PageVCs</span>
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/"><span style="color: #400080;">NSMutableArray</span></a> <span style="color: #002200;">*</span>tmpArray <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/"><span style="color: #400080;">NSMutableArray</span></a> array<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> i<span style="color: #002200;">=</span><span style="color: #2400d9;">0</span>; i&lt;<span style="color: #2400d9;">5</span>; i<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
	PageViewController <span style="color: #002200;">*</span>page <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>PageViewController alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>tmpArray addObject<span style="color: #002200;">:</span>page<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// set these as sub VCs</span>
<span style="color: #002200;">&#91;</span>container setSubViewControllers<span style="color: #002200;">:</span>tmpArray<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>So much for basic setup. Now let&#8217;s override the setter for the sub VCs to select the VC at index 0 and present it. Though we cannot present it in the setter, because the view might not have been loaded yet and so our _containerView IVAR is still nil.</p>

<div class="wp_codebox"><table><tr id="p622575"><td class="code" id="p6225code75"><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>setSubViewControllers<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>subViewControllers
<span style="color: #002200;">&#123;</span>
	_subViewControllers <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>subViewControllers copy<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>_selectedViewController<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #11740a; font-style: italic;">// TODO: remove previous VC</span>
	<span style="color: #002200;">&#125;</span>
&nbsp;
	_selectedViewController <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>subViewControllers objectAtIndex<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// cannot add here because the view might not have been loaded yet</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@synthesize</span> subViewControllers <span style="color: #002200;">=</span> _subViewControllers;</pre></td></tr></table></div>

<p>Instead we do it at the latest possible moment, that would be in the viewWillAppear because here we are guaranteed that the loadView has taken place already. A nice lazy thing, if we find that the selected VC already has self as the parent then there&#8217;s nothing to do.</p>

<div class="wp_codebox"><table><tr id="p622576"><td class="code" id="p6225code76"><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>viewWillAppear<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>animated
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>super viewWillAppear<span style="color: #002200;">:</span>animated<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>_selectedViewController.parentViewController <span style="color: #002200;">==</span> self<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #11740a; font-style: italic;">// nowthing to do</span>
		<span style="color: #a61390;">return</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// adjust the frame to fit in the container view</span>
	_selectedViewController.view.frame <span style="color: #002200;">=</span> _containerView.bounds;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// make sure that it resizes on rotation automatically</span>
	_selectedViewController.view.autoresizingMask <span style="color: #002200;">=</span> _containerView.autoresizingMask;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// add as child VC</span>
	<span style="color: #002200;">&#91;</span>self addChildViewController<span style="color: #002200;">:</span>_selectedViewController<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// add it to container view, calls willMoveToParentViewController for us</span>
	<span style="color: #002200;">&#91;</span>_containerView addSubview<span style="color: #002200;">:</span>_selectedViewController.view<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// notify it that move is done</span>
	<span style="color: #002200;">&#91;</span>_selectedViewController didMoveToParentViewController<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>The above shown sequence takes care of calling the viewWillAppear, viewDidAppear, willMoveToParentViewController and didMoveToParentViewController. Notice that all but the last are done for you automatically, but for some strange reason the didMove is not. So we have to do that manually. Upon starting our Demo we now see the VC at index 0.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-04-14-um-2.41.09-PM.png"><img src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-04-14-um-2.41.09-PM-232x300.png" alt="" title="Page VC presented" width="232" height="300" class="alignnone size-medium wp-image-6229" /></a></p>
<p>Next we add the capability to transition from one VC to the next. </p>
<h3>Transitioning</h3>
<p>To move between the child VCs we&#8217;ll add a swipe gesture recognizer to our container. If we swipe left we want to go to the VC with a lower index in the array. If we swipe right we want to go higher. No wrapping. In loadView we add:</p>

<div class="wp_codebox"><table><tr id="p622577"><td class="code" id="p6225code77"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// add gesture support</span>
UISwipeGestureRecognizer <span style="color: #002200;">*</span>swipeLeft <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UISwipeGestureRecognizer alloc<span style="color: #002200;">&#93;</span> initWithTarget<span style="color: #002200;">:</span>self action<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>swipeLeft<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
swipeLeft.direction <span style="color: #002200;">=</span> UISwipeGestureRecognizerDirectionLeft;
<span style="color: #002200;">&#91;</span>view addGestureRecognizer<span style="color: #002200;">:</span>swipeLeft<span style="color: #002200;">&#93;</span>;
&nbsp;
UISwipeGestureRecognizer <span style="color: #002200;">*</span>swipeRight <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UISwipeGestureRecognizer alloc<span style="color: #002200;">&#93;</span> initWithTarget<span style="color: #002200;">:</span>self action<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>swipeRight<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
swipeRight.direction <span style="color: #002200;">=</span> UISwipeGestureRecognizerDirectionRight;
<span style="color: #002200;">&#91;</span>view addGestureRecognizer<span style="color: #002200;">:</span>swipeRight<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>And the implementation of swipe is as follows. For simplicity&#8217;s sake we use two separate gesture recognizers because Apple does not provide an easy way to determine the swipe direction if you combine to directions.</p>

<div class="wp_codebox"><table><tr id="p622578"><td class="code" id="p6225code78"><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>swipeLeft<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UISwipeGestureRecognizer <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>gesture
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>gesture.state <span style="color: #002200;">==</span> UIGestureRecognizerStateRecognized<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		NSInteger index <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>_subViewControllers indexOfObject<span style="color: #002200;">:</span>_selectedViewController<span style="color: #002200;">&#93;</span>;
		index <span style="color: #002200;">=</span> MIN<span style="color: #002200;">&#40;</span>index<span style="color: #002200;">+</span><span style="color: #2400d9;">1</span>, <span style="color: #002200;">&#91;</span>_subViewControllers count<span style="color: #002200;">&#93;</span><span style="color: #002200;">-</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
&nbsp;
		UIViewController <span style="color: #002200;">*</span>newSubViewController <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>_subViewControllers objectAtIndex<span style="color: #002200;">:</span>index<span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #002200;">&#91;</span>self transitionFromViewController<span style="color: #002200;">:</span>_selectedViewController toViewController<span style="color: #002200;">:</span>newSubViewController<span style="color: #002200;">&#93;</span>; 
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>swipeRight<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UISwipeGestureRecognizer <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>gesture
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>gesture.state <span style="color: #002200;">==</span> UIGestureRecognizerStateRecognized<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		NSInteger index <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>_subViewControllers indexOfObject<span style="color: #002200;">:</span>_selectedViewController<span style="color: #002200;">&#93;</span>;
		index <span style="color: #002200;">=</span> MAX<span style="color: #002200;">&#40;</span>index<span style="color: #002200;">-</span><span style="color: #2400d9;">1</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
		UIViewController <span style="color: #002200;">*</span>newSubViewController <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>_subViewControllers objectAtIndex<span style="color: #002200;">:</span>index<span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #002200;">&#91;</span>self transitionFromViewController<span style="color: #002200;">:</span>_selectedViewController toViewController<span style="color: #002200;">:</span>newSubViewController<span style="color: #002200;">&#93;</span>; 
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>The logic to transition from one VC to another we package in transitionFromViewController:toViewController:. This is the really interesting part. There is a convenient method that again takes care of most of the boring work of adding and removing views. And again some non-obvious additional messaging is necessary to get it perfect.</p>

<div class="wp_codebox"><table><tr id="p622579"><td class="code" id="p6225code79"><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>transitionFromViewController<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIViewController <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>fromViewController toViewController<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIViewController <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>toViewController
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>fromViewController <span style="color: #002200;">==</span> toViewController<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #11740a; font-style: italic;">// cannot transition to same</span>
		<span style="color: #a61390;">return</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// animation setup</span>
	toViewController.view.frame <span style="color: #002200;">=</span> _containerView.bounds;
	toViewController.view.autoresizingMask <span style="color: #002200;">=</span> _containerView.autoresizingMask;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// notify</span>
	<span style="color: #002200;">&#91;</span>fromViewController willMoveToParentViewController<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>self addChildViewController<span style="color: #002200;">:</span>toViewController<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// transition</span>
	<span style="color: #002200;">&#91;</span>self transitionFromViewController<span style="color: #002200;">:</span>fromViewController
					  toViewController<span style="color: #002200;">:</span>toViewController
							  duration<span style="color: #002200;">:</span><span style="color: #2400d9;">1.0</span>
							   options<span style="color: #002200;">:</span>UIViewAnimationOptionTransitionCurlDown
							animations<span style="color: #002200;">:^</span><span style="color: #002200;">&#123;</span>
							<span style="color: #002200;">&#125;</span>
							completion<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span> finished<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
								<span style="color: #002200;">&#91;</span>toViewController didMoveToParentViewController<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;
								<span style="color: #002200;">&#91;</span>fromViewController removeFromParentViewController<span style="color: #002200;">&#93;</span>;
							<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>And with that we have our transitions in the can.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-04-14-um-3.27.33-PM.png"><img src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-04-14-um-3.27.33-PM-232x300.png" alt="" title="Transition working" width="232" height="300" class="alignnone size-medium wp-image-6234" /></a></p>
<p>You have a number of UIViewAnimationOptionTransition-s available, but you don&#8217;t have to settle for these. You can also pass 0 for the options and instead provide all animations you like the two views to execute in the animations block. </p>
<p>Before I discovered is method I was using the previous method of animating the views. Though this has a side-effect that we might not like in this case. Typically you want the &#8220;will&#8221; delegate methods to fire before the transition and the &#8220;did&#8221; to follow afterwards. If you animate the views yourself then iOS 5 will take care of sending these messages for you but it does so together. This looses us the ability to differentiate between stuff we want to do before and after the appearing and disappearing of the view controller.</p>
<h3>Conclusion</h3>
<p>It took me quite a bit of experimenting to also get all the messaging happening and equally balanced. The above sample has that working as it should.</p>
<p>But once you do figure out the two techniques outlined in this article you are on the road to implement your own view controller containment like you never did anything else. </p>
<p>One thing that I wasn&#8217;t able to figure out so far is why the transition method always adds the new view controller&#8217;s view to the container view controller&#8217;s main view. This simplifes the process somewhat because you don&#8217;t have to know at which stage in the transition it is ok to add and remove the views. But at the same time you might have a situation where you don&#8217;t want the animation to occur over the entire area of the container view controller. </p>
<p>For this scenario I can only think of covering up the parts with extra sub views. Or we could stack multiple container view controllers and have one to only cover the region where where have the container view. This could then clip its subviews and thus be only care for this area.</p>
<p>The main advantage of any kind of view controller containment is that rotation messages (should|will|did) reach the lowest leaves of your view controller tree. Unless you disable that by means of overriding automaticallyForwardAppearanceAndRotationMethodsToChildViewControllers and returning NO.</p>
<p>But who would really want that when we have waited for so long for public API to have these being forwarded? Working with view controller containers I get a feeling that they greatly simplified creating complex user interfaces consisting of multiple parts.</p>
<p>The project for this tutorial is in <a href="https://github.com/Cocoanetics/Examples">my Examples GitHub repository</a>.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=6225&amp;md5=46459a7a8ca486564795a0f703b323b6" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/04/containing-viewcontrollers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F04%2Fcontaining-viewcontrollers%2F&amp;language=en_GB&amp;category=text&amp;title=Containing+ViewControllers&amp;description=For+a+project+that+I+am+currently+working+on+I+needed+to+implement+a+custom+container+view+controller.+I+was+feeling+my+way+forward+in+the+dark+for+the+most...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>DTMorseKeyboard Tutorial</title>
		<link>http://www.cocoanetics.com/2012/04/dtmorsekeyboard-tutorial/</link>
		<comments>http://www.cocoanetics.com/2012/04/dtmorsekeyboard-tutorial/#comments</comments>
		<pubDate>Sun, 01 Apr 2012 21:55:43 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=6188</guid>
		<description><![CDATA[Inspired by the Gmail Tap April Fools joke by Google I felt inspired to program the same thing for iOS. There we have custom input views as well as the UIKeyInput protocol and so I figured it should be an easy undertaking. The whole affair took slightly more than one hour and I was hoping to record it in 1 second intervals with ScreenNinja. Unfortunately it seems that this otherwise fabulous app crapped out on me. I later discovered that the MOV file had actually finished before the crash, so to my delight (and hopefully yours too) you can follow this tutorial on YouTube. &#160; In the video you see the whole process from start to finish. Let me just offer some clarifications in this post so that you better understand what I am doing. http://www.youtube.com/watch?v=w5lRUE1Xet8 In iOS Apple provides us with two protocols, UIKeyInput for inputting single key strokes and UITextInput for everything that&#8217;s more than single keys, like text selection, auto correction etc. As part of UITextInput each conforming UIView implements an inputView property that can be any UIView. If set this inputView is shown instead of the standard keyboard, if not then you see the keyboard. So for our example all we need is a UIView with one button for the Morse button. The Gmail Tap prank interface uses two buttons, one for a dot, one for a dash. When researching Morse Code on Wikipedia I found one slight problem with this approach. Individual letters have to have a slight pause from each other because otherwise we wouldn&#8217;t know if by a dot the user intends to write an E or one of the other dozen or so combinations that have a dot as the first part of a sequence. The Morse alphabet doesn&#8217;t just consist of 2 letters, but rather it uses 3 which are &#8220;dit&#8221;, &#8220;dah&#8221; and a silent pause. Given that &#8220;dit&#8221; is the shortest element, a &#8220;dah&#8221; is three times as long. Sequence elements are spaced one &#8220;dit&#8221; apart, Letters are spaced one &#8220;dah&#8221; apart and the length of 7 &#8220;dits&#8221; signifies a word break. Really, I am not making this up! First step is to override canBecomeFirstResponder and return YES. For simplicy I just wired up the UIControlEventTouchUpInside and the UIControlEventTouchDown to two methods and I&#8217;m using the time interval between the touch down and the touch up to determine if we saw a &#8220;dit&#8221; or &#8220;dah&#8221;. A bit of pause handling with performSelector:withObject:afterDelay: was necessary to get the breaks decoded. Then there is a lookup table from which to draw the actual letters once a letter break is encountered. + &#40;void&#41;initialize &#123; morseLookup = &#91;NSDictionary dictionaryWithObjectsAndKeys:@&#34;a&#34;, @&#34;··−·&#34;, @&#34;b&#34;,@&#34;−···&#34;, @&#34;c&#34;,@&#34;−·−·&#34;, @&#34;d&#34;,@&#34;−··&#34;, @&#34;e&#34;,@&#34;·&#34;, @&#34;f&#34;,@&#34;··−·&#34;, @&#34;g&#34;,@&#34;−−·&#34;, @&#34;i&#34;,@&#34;··&#34;, @&#34;j&#34;,@&#34;·−−−&#34;, @&#34;k&#34;,@&#34;−·−&#34;, @&#34;l&#34;,@&#34;·−··&#34;, @&#34;m&#34;,@&#34;−−&#34;, @&#34;n&#34;,@&#34;−·&#34;, @&#34;o&#34;,@&#34;−−−&#34;, @&#34;p&#34;,@&#34;·−−·&#34;, @&#34;q&#34;,@&#34;−−·−&#34;, @&#34;r&#34;,@&#34;·−·&#34;, @&#34;s&#34;,@&#34;···&#34;, @&#34;t&#34;,@&#34;−&#34;, @&#34;u&#34;,@&#34;··−&#34;, @&#34;v&#34;,@&#34;···−&#34;, @&#34;w&#34;,@&#34;·−−&#34;, @&#34;x&#34;,@&#34;−··−&#34;, @&#34;y&#34;,@&#34;−·−−&#34;, @&#34;z&#34;,@&#34;−−··&#34;, @&#34;0&#34;,@&#34;−−−−−&#34;, @&#34;1&#34;,@&#34;·−−−−&#34;, @&#34;2&#34;,@&#34;··−−−&#34;, @&#34;3&#34;,@&#34;···−−&#34;, @&#34;4&#34;,@&#34;····−&#34;, @&#34;5&#34;,@&#34;·····&#34;, @&#34;6&#34;,@&#34;−····&#34;, @&#34;7&#34;,@&#34;−−···&#34;, @&#34;8&#34;,@&#34;−−−··&#34;, @&#34;9&#34;,@&#34;−−−−·&#34;, nil&#93;; &#160; for &#40;NSString *oneSequence in &#91;morseLookup allKeys&#93;&#41; &#123; _longestMorseSequence = MAX&#40;_longestMorseSequence, &#91;oneSequence length&#93;&#41;; &#125; &#125; The final piece of the puzzle is that we somehow need to have a pointer to the text control so that we can insert the detected characters. I was puzzled by the fact there does not seem to be an obvious method to do that. So I went for the obvious method of setting it in the init. The input delegate (e.g. a UITextField) has to be compliant with the UIKeyInput protocol and therefore we know that it must have an insertText: method. This will insert the passed string at the current cursor position. Conclusion Turns out the by far hardest part of making our own custom keyboard is the input logic, which itself becomes way more complicated by having to invent algorithms to decode Morse sequences. There are several improvements that spring to mind right away. Auto-Completion would be one where it could show a decreasing number of possible sequences based on the sequence for a single letter so far. Maybe that could be shown if the finger is lifted outside of the button. Another question to tackle is how to actually delete text, the backspace key if you will. Maybe by doing a &#8220;dit&#8221; that begins on the button, but ends outside to the left of it? Finally there should be no set amount of time for a &#8220;dit&#8221;, experienced Morse-o-graphers can have much shorter dits as long as the relation of dits, dats and pauses remains mostly constant. In this tutorial I went for the easiest method of simply using the latest dit&#8217;s duration, but it would be nice to average this over time. Source code of the full project is available on GitHub.]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/04/dtmorsekeyboard-tutorial/"></g:plusone></div><p>Inspired by the <a href="http://mail.google.com/mail/help/promos/tap/index.html">Gmail Tap</a> April Fools joke by Google I felt inspired to program the same thing for iOS. There we have custom input views as well as the UIKeyInput protocol and so I figured it should be an easy undertaking.</p>
<p>The whole affair took slightly more than one hour and I was hoping to record it in 1 second intervals with ScreenNinja. Unfortunately it seems that this otherwise fabulous app crapped out on me. I later discovered that the MOV file had actually finished before the crash, so to my delight (and hopefully yours too) you can follow this tutorial on YouTube.</p>
<p><span id="more-6188"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>In the video you see the whole process from start to finish. Let me just offer some clarifications in this post so that you better understand what I am doing.</p>
<p><a href="http://www.youtube.com/watch?v=w5lRUE1Xet8&#038;fmt=18">http://www.youtube.com/watch?v=w5lRUE1Xet8</a></p>
<p>In iOS Apple provides us with two protocols, UIKeyInput for inputting single key strokes and UITextInput for everything that&#8217;s more than single keys, like text selection, auto correction etc. As part of UITextInput each conforming UIView implements an inputView property that can be any UIView.</p>
<p>If set this inputView is shown instead of the standard keyboard, if not then you see the keyboard. So for our example all we need is a UIView with one button for the Morse button.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-04-01-um-22.44.07.png"><img class="alignnone size-full wp-image-6190" title="Morse Button UI" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-04-01-um-22.44.07.png" alt="" width="396" height="744" /></a></p>
<p>The Gmail Tap prank interface uses two buttons, one for a dot, one for a dash. When researching <a href="http://en.wikipedia.org/wiki/Morse_code">Morse Code</a> on Wikipedia I found one slight problem with this approach. Individual letters have to have a slight pause from each other because otherwise we wouldn&#8217;t know if by a dot the user intends to write an E or one of the other dozen or so combinations that have a dot as the first part of a sequence.</p>
<p>The Morse alphabet doesn&#8217;t just consist of 2 letters, but rather it uses 3 which are &#8220;dit&#8221;, &#8220;dah&#8221; and a silent pause. Given that &#8220;dit&#8221; is the shortest element, a &#8220;dah&#8221; is three times as long. Sequence elements are spaced one &#8220;dit&#8221; apart, Letters are spaced one &#8220;dah&#8221; apart and the length of 7 &#8220;dits&#8221; signifies a word break. Really, I am not making this up!</p>
<p>First step is to override canBecomeFirstResponder and return YES.</p>
<p>For simplicy I just wired up the UIControlEventTouchUpInside and the UIControlEventTouchDown to two methods and I&#8217;m using the time interval between the touch down and the touch up to determine if we saw a &#8220;dit&#8221; or &#8220;dah&#8221;. A bit of pause handling with performSelector:withObject:afterDelay: was necessary to get the breaks decoded.</p>
<p>Then there is a lookup table from which to draw the actual letters once a letter break is encountered.</p>

<div class="wp_codebox"><table><tr id="p618892"><td class="code" id="p6188code92"><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>initialize
<span style="color: #002200;">&#123;</span>
	morseLookup <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/"><span style="color: #400080;">NSDictionary</span></a> dictionaryWithObjectsAndKeys<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;a&quot;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;··−·&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;b&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−···&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;c&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−·−·&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;d&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−··&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;e&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;·&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;f&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;··−·&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;g&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−−·&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;i&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;··&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;j&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;·−−−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;k&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−·−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;l&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;·−··&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;m&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;n&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−·&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;o&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−−−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;p&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;·−−·&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;q&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−−·−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;r&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;·−·&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;s&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;···&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;t&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;u&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;··−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;v&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;···−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;w&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;·−−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;x&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−··−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;y&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−·−−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;z&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−−··&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;0&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−−−−−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;1&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;·−−−−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;2&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;··−−−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;3&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;···−−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;4&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;····−&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;5&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;·····&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;6&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−····&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;7&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−−···&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;8&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−−−··&quot;</span>,
						<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;9&quot;</span>,<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;−−−−·&quot;</span>,
						<span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>oneSequence <span style="color: #a61390;">in</span> <span style="color: #002200;">&#91;</span>morseLookup allKeys<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		_longestMorseSequence <span style="color: #002200;">=</span> MAX<span style="color: #002200;">&#40;</span>_longestMorseSequence, <span style="color: #002200;">&#91;</span>oneSequence length<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>The final piece of the puzzle is that we somehow need to have a pointer to the text control so that we can insert the detected characters. I was puzzled by the fact there does not seem to be an obvious method to do that. So I went for the obvious method of setting it in the init.</p>
<p>The input delegate (e.g. a UITextField) has to be compliant with the UIKeyInput protocol and therefore we know that it must have an insertText: method. This will insert the passed string at the current cursor position.</p>
<h3>Conclusion</h3>
<p>Turns out the by far hardest part of making our own custom keyboard is the input logic, which itself becomes way more complicated by having to invent algorithms to decode Morse sequences. </p>
<p>There are several improvements that spring to mind right away. Auto-Completion would be one where it could show a decreasing number of possible sequences based on the sequence for a single letter so far. Maybe that could be shown if the finger is lifted outside of the button.</p>
<p>Another question to tackle is how to actually delete text, the backspace key if you will. Maybe by doing a &#8220;dit&#8221; that begins on the button, but ends outside to the left of it?</p>
<p>Finally there should be no set amount of time for a &#8220;dit&#8221;, experienced Morse-o-graphers can have much shorter dits as long as the relation of dits, dats and pauses remains mostly constant. In this tutorial I went for the easiest method of simply using the latest dit&#8217;s duration, but it would be nice to average this over time.</p>
<p>Source code of the full project is <a href="https://github.com/Cocoanetics/DTMorseKeyboard">available on GitHub</a>.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=6188&amp;md5=5f53a0e9042a02307fabf95d8e69b5be" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/04/dtmorsekeyboard-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F04%2Fdtmorsekeyboard-tutorial%2F&amp;language=en_GB&amp;category=text&amp;title=DTMorseKeyboard+Tutorial&amp;description=Inspired+by+the+Gmail+Tap+April+Fools+joke+by+Google+I+felt+inspired+to+program+the+same+thing+for+iOS.+There+we+have+custom+input+views+as+well+as+the...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Reading and Writing Extended File Attributes</title>
		<link>http://www.cocoanetics.com/2012/03/reading-and-writing-extended-file-attributes/</link>
		<comments>http://www.cocoanetics.com/2012/03/reading-and-writing-extended-file-attributes/#comments</comments>
		<pubDate>Tue, 06 Mar 2012 14:34:22 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=6064</guid>
		<description><![CDATA[The file systems of iOS and Mac both use HFS+ as file system, with only one small difference. iOS uses case-sensitive file names, Mac doesn&#8217;t by default. Both have a feature called &#8220;Extended File Attributes&#8221; that allow you to set custom values by key. Apple generally ignored this functionality and it was only briefly &#8211; in 5.0.1 &#8211; that they actually used an extended attributed for something. The &#8220;com.apple.MobileBackup&#8221; extended attribute served as a stop-gap-measure to mark files that should not be backed up. Though this was very short lived. I was facing the problem myself that I needed to save the ETag for an image that I downloaded from the web somewhere. And I wanted to do that elegantly, somehow together with the file itself and in a way that would simply work. &#160; Well, the best way for achieving this simple goal was to save the ETag value in the extended file attributes. This way you don&#8217;t have to keep track of a separate file or storage for the value. If the file is deleted, then that takes care of the extended attributes as well. Extended attributes are managed with C-API defined in sys/xattr.h, so most of the work in translating to and from Objective-C is converting strings. To set an attribute you do this: const char *attrName = &#91;attribute UTF8String&#93;; const char *filePath = &#91;_path fileSystemRepresentation&#93;; &#160; const char *val = &#91;value UTF8String&#93;; &#160; int result = setxattr&#40;filePath, attrName, val, strlen&#40;val&#41;, 0, 0&#41;; Note that result has to be a signed integer because it returns -1 in case of error. The above assumes that you want to set a string as value which is the most versatile. But in fact you can set any kind of byte data because you specify a pointer to the first byte and then number of bytes to write. So you can also set an integer like this: int val=1; int result = setxattr&#40;filePath, attrName, &#38;val, sizeof&#40;val&#41;, 0, 0&#41;; In my special case I was content with setting an NSString. I didn&#8217;t see any way how you could know from the data from what bytes it was actually set. I guess you have to make your own rules and only access/decode your own extended attributes. To retrieve the extended attribute value you do this: const char *attrName = &#91;attribute UTF8String&#93;; const char *filePath = &#91;_path fileSystemRepresentation&#93;; &#160; // get size of needed buffer int bufferLength = getxattr&#40;filePath, attrName, NULL, 0, 0, 0&#41;; &#160; // make a buffer of sufficient length char *buffer = malloc&#40;bufferLength&#41;; &#160; // now actually get the attribute string getxattr&#40;filePath, attrName, buffer, 255, 0, 0&#41;; &#160; // convert to NSString NSString *retString = &#91;&#91;NSString alloc&#93; initWithBytes:buffer length:bufferLength encoding:NSUTF8StringEncoding&#93;; &#160; // release buffer free&#40;buffer&#41;; Here you see getxattr actually being called twice. If you don&#8217;t set a pointer to a buffer this retrieves the size of the value in bytes for the attribute. So you can malloc a sufficiently large buffer and then get this filled to the brim on the second call. All commands in xattr.h have two variants, one with a file path and a second with with a file descriptor. The latter would be used in cases where you want to keep the file descriptor (sort of a handle to the file) around doing more work. But we can ignore these. There are also two more functions, for sake of completeness, one to remove an extended attribute, one to get a list of all keys. I contemplated for a while to make an API similar to NSFileManager, but since we don&#8217;t know the data type (unless we save that somewhere) there is little use to build a method that sets or retrieves and entire dictionary of keys and values. Also, for now, I only need to save and retrieve a single string. I created a documented wrapper for handling extended file attributes in DTFoundation and I named it DTExtendedFileAttributes.]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/03/reading-and-writing-extended-file-attributes/"></g:plusone></div><p>The file systems of iOS and Mac both use HFS+ as file system, with only one small difference. iOS uses case-sensitive file names, Mac doesn&#8217;t by default. Both have a feature called &#8220;Extended File Attributes&#8221; that allow you to set custom values by key.</p>
<p>Apple generally ignored this functionality and it was only briefly &#8211; in 5.0.1 &#8211; that they actually used an extended attributed for something. The &#8220;com.apple.MobileBackup&#8221; extended attribute served as a stop-gap-measure to mark files that should not be backed up. Though this was very short lived.</p>
<p>I was facing the problem myself that I needed to save the ETag for an image that I downloaded from the web somewhere. And I wanted to do that elegantly, somehow together with the file itself and in a way that would simply work.</p>
<p><span id="more-6064"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>Well, the best way for achieving this simple goal was to save the ETag value in the extended file attributes. This way you don&#8217;t have to keep track of a separate file or storage for the value. If the file is deleted, then that takes care of the extended attributes as well.</p>
<p>Extended attributes are managed with C-API defined in sys/xattr.h, so most of the work in translating to and from Objective-C is converting strings.</p>
<p>To set an attribute you do this:</p>

<div class="wp_codebox"><table><tr id="p606497"><td class="code" id="p6064code97"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">const</span> <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>attrName <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>attribute UTF8String<span style="color: #002200;">&#93;</span>;
<span style="color: #a61390;">const</span> <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>filePath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>_path fileSystemRepresentation<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #a61390;">const</span> <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>val <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>value UTF8String<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #a61390;">int</span> result <span style="color: #002200;">=</span> setxattr<span style="color: #002200;">&#40;</span>filePath, attrName, val, <a href="http://www.opengroup.org/onlinepubs/009695399/functions/strlen.html"><span style="color: #a61390;">strlen</span></a><span style="color: #002200;">&#40;</span>val<span style="color: #002200;">&#41;</span>, <span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>Note that result has to be a signed integer because it returns -1 in case of error.</p>
<p>The above assumes that you want to set a string as value which is the most versatile. But in fact you can set any kind of byte data because you specify a pointer to the first byte and then number of bytes to write. So you can also set an integer like this:</p>

<div class="wp_codebox"><table><tr id="p606498"><td class="code" id="p6064code98"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">int</span> val<span style="color: #002200;">=</span><span style="color: #2400d9;">1</span>;
<span style="color: #a61390;">int</span> result <span style="color: #002200;">=</span> setxattr<span style="color: #002200;">&#40;</span>filePath, attrName, <span style="color: #002200;">&amp;</span>val, <a href="http://www.opengroup.org/onlinepubs/009695399/functions/sizeof.html"><span style="color: #a61390;">sizeof</span></a><span style="color: #002200;">&#40;</span>val<span style="color: #002200;">&#41;</span>, <span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>In my special case I was content with setting an NSString. I didn&#8217;t see any way how you could know from the data from what bytes it was actually set. I guess you have to make your own rules and only access/decode your own extended attributes.</p>
<p>To retrieve the extended attribute value you do this:</p>

<div class="wp_codebox"><table><tr id="p606499"><td class="code" id="p6064code99"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">const</span> <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>attrName <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>attribute UTF8String<span style="color: #002200;">&#93;</span>;
<span style="color: #a61390;">const</span> <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>filePath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>_path fileSystemRepresentation<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// get size of needed buffer</span>
<span style="color: #a61390;">int</span> bufferLength <span style="color: #002200;">=</span> getxattr<span style="color: #002200;">&#40;</span>filePath, attrName, <span style="color: #a61390;">NULL</span>, <span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// make a buffer of sufficient length</span>
<span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>buffer <span style="color: #002200;">=</span> <a href="http://www.opengroup.org/onlinepubs/009695399/functions/malloc.html"><span style="color: #a61390;">malloc</span></a><span style="color: #002200;">&#40;</span>bufferLength<span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// now actually get the attribute string</span>
getxattr<span style="color: #002200;">&#40;</span>filePath, attrName, buffer, <span style="color: #2400d9;">255</span>, <span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// convert to NSString</span>
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>retString <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> alloc<span style="color: #002200;">&#93;</span> initWithBytes<span style="color: #002200;">:</span>buffer length<span style="color: #002200;">:</span>bufferLength encoding<span style="color: #002200;">:</span>NSUTF8StringEncoding<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// release buffer</span>
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/free.html"><span style="color: #a61390;">free</span></a><span style="color: #002200;">&#40;</span>buffer<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>Here you see getxattr actually being called twice. If you don&#8217;t set a pointer to a buffer this retrieves the size of the value in bytes for the attribute. So you can malloc a sufficiently large buffer and then get this filled to the brim on the second call.</p>
<p>All commands in xattr.h have two variants, one with a file path and a second with with a file descriptor. The latter would be used in cases where you want to keep the file descriptor (sort of a handle to the file) around doing more work. But we can ignore these.</p>
<p>There are also two more functions, for sake of completeness, one to remove an extended attribute, one to get a list of all keys. I contemplated for a while to make an API similar to NSFileManager, but since we don&#8217;t know the data type (unless we save that somewhere) there is little use to build a method that sets or retrieves and entire dictionary of keys and values. Also, for now, I only need to save and retrieve a single string.</p>
<p>I created a <a href="http://cocoanetics.github.com/DTFoundation/Classes/DTExtendedFileAttributes.html">documented wrapper</a> for handling extended file attributes in <a href="https://github.com/cocoanetics/dtfoundation">DTFoundation</a> and I named it <strong>DTExtendedFileAttributes</strong>.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=6064&amp;md5=47cdc20fbfd1c3d8a3a8c2e89f60f774" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/03/reading-and-writing-extended-file-attributes/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F03%2Freading-and-writing-extended-file-attributes%2F&amp;language=en_GB&amp;category=text&amp;title=Reading+and+Writing+Extended+File+Attributes&amp;description=The+file+systems+of+iOS+and+Mac+both+use+HFS%2B+as+file+system%2C+with+only+one+small+difference.+iOS+uses+case-sensitive+file+names%2C+Mac+doesn%26%238217%3Bt+by+default.+Both+have+a...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Quick Batch Version Bump</title>
		<link>http://www.cocoanetics.com/2012/03/quick-batch-version-bump/</link>
		<comments>http://www.cocoanetics.com/2012/03/quick-batch-version-bump/#comments</comments>
		<pubDate>Mon, 05 Mar 2012 09:40:56 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=6046</guid>
		<description><![CDATA[On my iCatalog project I have more than 40 targets (FOURTY!), all with individual info.plist. Let me share a quick command line script that lets me simultaneously bump the software version to a different value for all targets at the same time. This has proven extremely helpful. &#160; The script I use uses the defaults tool to write the new value into the plists and then converts it back to text xml plist format. bump_version_to.sh #!/bin/sh &#160; if [ &#34;$#&#34; -ne 1 ] then echo &#34;Usage: bump_version_to &#60;version&#62;&#34; exit 1 fi &#160; for FILE in `ls */*Info.plist` do INFO_PLIST=`pwd`/${FILE%.*} defaults write &#34;$INFO_PLIST&#34; CFBundleVersion &#34;$1&#34; plutil -convert xml1 &#34;$INFO_PLIST.plist&#34; done Put this script into your project root. It expects the info.plist files to be one level below it. Make it executable with chmod +x. Run it passing the new version string. Boom!]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/03/quick-batch-version-bump/"></g:plusone></div><p>On my iCatalog project I have more than 40 targets (FOURTY!), all with individual info.plist. Let me share a quick command line script that lets me simultaneously bump the software version to a different value for all targets at the same time. This has proven extremely helpful.</p>
<p><span id="more-6046"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>The script I use uses the defaults tool to write the new value into the plists and then converts it back to text xml plist format.</p>
<p><strong>bump_version_to.sh</strong></p>

<div class="wp_codebox"><table><tr id="p6046104"><td class="code" id="p6046code104"><pre class="sh" style="font-family:monospace;">#!/bin/sh
&nbsp;
if [ &quot;$#&quot; -ne 1 ]
then
        echo &quot;Usage: bump_version_to &lt;version&gt;&quot;
        exit 1
fi
&nbsp;
for FILE in `ls */*Info.plist`
do
        INFO_PLIST=`pwd`/${FILE%.*}
        defaults write &quot;$INFO_PLIST&quot; CFBundleVersion &quot;$1&quot;
        plutil -convert xml1 &quot;$INFO_PLIST.plist&quot;
done</pre></td></tr></table></div>

<p>Put this script into your project root. It expects the info.plist files to be one level below it. Make it executable with chmod +x. Run it passing the new version string. Boom!</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=6046&amp;md5=0efd57257e2e8adad7b0cb856164c197" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/03/quick-batch-version-bump/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F03%2Fquick-batch-version-bump%2F&amp;language=en_GB&amp;category=text&amp;title=Quick+Batch+Version+Bump&amp;description=On+my+iCatalog+project+I+have+more+than+40+targets+%28FOURTY%21%29%2C+all+with+individual+info.plist.+Let+me+share+a+quick+command+line+script+that+lets+me+simultaneously+bump+the+software...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Block Retain Loop</title>
		<link>http://www.cocoanetics.com/2012/03/block-retain-loop/</link>
		<comments>http://www.cocoanetics.com/2012/03/block-retain-loop/#comments</comments>
		<pubDate>Fri, 02 Mar 2012 08:17:50 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=6021</guid>
		<description><![CDATA[I was getting reports about DTCoreText having leaks. Not something I like to wake up to, to be honest. So I dived right in with Instruments and the Leaks tool. I am going to share with you something that I learned about Leaks and Blocks that might save you much trouble if you check for that first the next time you profile any app. &#160; I fired up Instruments with the DTCoreText demo app running in simulator and I was dumbfounded. Lots of small red bars told of unchecked leaks. But what was even more unnerving was the sheer amount of different objects that got leaked. No way that all these different &#8220;Responsible Frames&#8221; where all leaking. I did what every engineer does at first: find somebody else to blame. So I pointed the finger at Apple, because obviously NSScanner, NSDictionary and NSString are &#8220;leaking like crazy&#8221;. What other reason could there be for NSDictionary leaking 64 Bytes on every mutableCopy? In my desperation I wasted about half a day trying to rewrite methods to leak less, like replace NSDictionary&#8217;s mutableCopy with initWithDictionary. But the only thing this achieved was to move the leaks elsewhere. Like a sinking boat I found myself unable to plug any holes because for each plugged one a new leak would form. Rule number 2 for engineers is: if you cannot achieve perfection, then at least rationalize it as &#8220;good enough&#8221;. Surely it cannot be a problem leaking 192 Bytes every now and then. We all shipped apps leaking more than that, right? So, it&#8217;s all Apple&#8217;s fault and my code is good enough&#8230;. The Retain Loop Loupe But then &#8211; while aimlessly clicking around the Instruments interface &#8211; I discovered the &#8220;Cycles &#38; Roots&#8221; tool. Bam! Next to an amazing Picasso I saw some Complex and some Simple Cycles. But the flow chart made a light go on in my head. Obviously the root cause was DTHTMLAttributedStringBuilder having a dictionary that held onto an NSMallocBlock that referred back to the builder class, a classical retain loop. They should name this graphic &#8220;The Retain Loupe&#8221; because it magnified the problem sufficiently so that even us dumb developers would get it. To understand what the above means let me briefly explain an architecture choice I made in the attributed string builder class. In the original code I had an enormous if-else if-else if-etc. tree checking for all different kinds of HTML tag names. I changed all this by having two dictionaries of handlers for starting and ending of tags. Each dictionary contains the blocks to be executed when the opening or closing of certain tags are encountered. @implementation DTHTMLAttributedStringBuilder &#123; // parsing state, accessed from inside blocks DTHTMLElement *currentTag; &#160; // lookup table for blocks that deal with begin and end tags NSMutableDictionary *_tagStartHandlers; NSMutableDictionary *_tagEndHandlers; &#125; &#160; - &#40;void&#41;_registerTagStartHandlers &#123; void &#40;^blockquoteBlock&#41;&#40;void&#41; = ^ &#123; currentTag.paragraphStyle.headIndent += 25.0 * textScale; currentTag.paragraphStyle.firstLineHeadIndent = currentTag.paragraphStyle.headIndent; currentTag.paragraphStyle.paragraphSpacing = defaultFontDescriptor.pointSize; &#125;; &#160; &#91;_tagStartHandlers setObject:&#91;blockquoteBlock copy&#93; forKey:@&#34;blockquote&#34;&#93;; &#160; // ... &#125; So in the parser delegate method for opening of tags I can see if there is a block registered for a given tag and execute it if it is. - &#40;void&#41;parser:&#40;DTHTMLParser *&#41;parser didStartElement:&#40;NSString *&#41;elementName attributes:&#40;NSDictionary *&#41;attributeDict &#123; // find block to execute for this tag if any void &#40;^tagBlock&#41;&#40;void&#41; = &#91;_tagStartHandlers objectForKey:elementName&#93;; &#160; if &#40;tagBlock&#41; &#123; tagBlock&#40;&#41;; &#125; &#125; Isn&#8217;t it beautiful? When the blocks are created the compiler checks which variables are used. If you use a local variable then it is copied. Any objects used thusly are also retained during the lifetime of the block. If you use an instance variable (currentTag) then this also means that self will be captured and retained. The reason for this is that the runtime needs to make sure that all needed objects stay around while the block lives. Michael Mangold points us to Lecture 10 of Standford&#8217;s iOS Development course, which explains the block basics as well. Simple Fix The problem with this is that each of these blocks that accesses an ivar retains self, but the string builder class also retains the dictionaries which in turn retain the blocks. Vicious loop, fortunately with a simple fix. The simple fix for this is to make sure that the two dictionaries are released when no longer needed. In ARC you force a release by nilling the only reference to them. - &#40;BOOL&#41;buildString &#123; // register default handlers &#91;self _registerTagStartHandlers&#93;; &#91;self _registerTagEndHandlers&#93;; &#160; // string building &#160; // clean up handlers because they retained self _tagStartHandlers = nil; _tagEndHandlers = nil; &#160; return result; &#125; That&#8217;s all it takes, boom! Gone are all leaks. So these &#8220;Leaks&#8221; where no real leaks. They where just the interim objects that made up the NSAttributedString that the string builder produced while building the string from HTML. [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/03/block-retain-loop/"></g:plusone></div><p>I was getting reports about DTCoreText having leaks. Not something I like to wake up to, to be honest. So I dived right in with Instruments and the Leaks tool. I am going to share with you something that I learned about Leaks and Blocks that might save you much trouble if you check for that first the next time you profile any app.</p>
<p><span id="more-6021"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>I fired up Instruments with the DTCoreText demo app running in simulator and I was dumbfounded. Lots of small red bars told of unchecked leaks. But what was even more unnerving was the sheer amount of different objects that got leaked. No way that all these different &#8220;Responsible Frames&#8221; where all leaking.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-03-02-um-08.14.23.png"><img class="alignnone size-full wp-image-6022" title="Leaks" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-03-02-um-08.14.23.png" alt="" width="685" height="528" /></a></p>
<p>I did what every engineer does at first: <strong>find somebody else to blame</strong>. So I pointed the finger at Apple, because <em>obviously</em> NSScanner, NSDictionary and NSString are &#8220;leaking like crazy&#8221;. What other reason could there be for NSDictionary leaking 64 Bytes on every mutableCopy?</p>
<p>In my desperation I wasted about half a day trying to rewrite methods to leak less, like replace NSDictionary&#8217;s mutableCopy with initWithDictionary. But the only thing this achieved was to move the leaks elsewhere. Like a sinking boat I found myself unable to plug any holes because for each plugged one a new leak would form.</p>
<p>Rule number 2 for engineers is: if you cannot achieve perfection, then at least <strong>rationalize it as &#8220;good enough&#8221;</strong>. Surely it cannot be a problem leaking 192 Bytes every now and then. We all shipped apps leaking more than that, right?</p>
<p>So, it&#8217;s all Apple&#8217;s fault and my code is good enough&#8230;.</p>
<h3>The Retain Loop Loupe</h3>
<p>But then &#8211; while aimlessly clicking around the Instruments interface &#8211; I discovered the &#8220;Cycles &amp; Roots&#8221; tool. Bam!</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-03-02-um-08.25.14.png"><img class="alignnone size-full wp-image-6025" title="Cycles &amp; Roots" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-03-02-um-08.25.14.png" alt="" width="680" height="421" /></a></p>
<p>Next to an amazing Picasso I saw some Complex and some Simple Cycles. But the flow chart made a light go on in my head. Obviously the root cause was DTHTMLAttributedStringBuilder having a dictionary that held onto an NSMallocBlock that referred back to the builder class, a classical <strong>retain loop</strong>. They should name this graphic &#8220;The Retain Loupe&#8221; because it magnified the problem sufficiently so that even us dumb developers would get it.</p>
<p>To understand what the above means let me briefly explain an architecture choice I made in the attributed string builder class. In the original code I had an enormous if-else if-else if-etc. tree checking for all different kinds of HTML tag names. I changed all this by having two dictionaries of handlers for starting and ending of tags. Each dictionary contains the blocks to be executed when the opening or closing of certain tags are encountered.</p>

<div class="wp_codebox"><table><tr id="p6021111"><td class="code" id="p6021code111"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> DTHTMLAttributedStringBuilder
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// parsing state, accessed from inside blocks</span>
	DTHTMLElement <span style="color: #002200;">*</span>currentTag;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// lookup table for blocks that deal with begin and end tags</span>
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/"><span style="color: #400080;">NSMutableDictionary</span></a> <span style="color: #002200;">*</span>_tagStartHandlers;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/"><span style="color: #400080;">NSMutableDictionary</span></a> <span style="color: #002200;">*</span>_tagEndHandlers;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>_registerTagStartHandlers
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">void</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span>blockquoteBlock<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">=</span> <span style="color: #002200;">^</span>
	<span style="color: #002200;">&#123;</span>
		currentTag.paragraphStyle.headIndent <span style="color: #002200;">+=</span> <span style="color: #2400d9;">25.0</span> <span style="color: #002200;">*</span> textScale;
		currentTag.paragraphStyle.firstLineHeadIndent <span style="color: #002200;">=</span> currentTag.paragraphStyle.headIndent;
		currentTag.paragraphStyle.paragraphSpacing <span style="color: #002200;">=</span> defaultFontDescriptor.pointSize;
	<span style="color: #002200;">&#125;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>_tagStartHandlers setObject<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>blockquoteBlock copy<span style="color: #002200;">&#93;</span> forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;blockquote&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// ...</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>So in the parser delegate method for opening of tags I can see if there is a block registered for a given tag and execute it if it is.</p>

<div class="wp_codebox"><table><tr id="p6021112"><td class="code" id="p6021code112"><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>parser<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>DTHTMLParser <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>parser didStartElement<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>elementName attributes<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/"><span style="color: #400080;">NSDictionary</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>attributeDict
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// find block to execute for this tag if any</span>
	<span style="color: #a61390;">void</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span>tagBlock<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>_tagStartHandlers objectForKey<span style="color: #002200;">:</span>elementName<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>tagBlock<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		tagBlock<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Isn&#8217;t it beautiful?</p>
<p>When the blocks are created the compiler checks which variables are used. If you use a local variable then it is copied. Any objects used thusly are also retained during the lifetime of the block. If you use an instance variable (currentTag) then this also means that self will be captured and retained. The reason for this is that the runtime needs to make sure that all needed objects stay around while the block lives.</p>
<p>Michael Mangold points us to <a href="http://itunes.apple.com/us/podcast/10.-blocks-multithreading/id473757255?i=107327893">Lecture 10 of Standford&#8217;s iOS Development course</a>, which explains the block basics as well.</p>
<h3>Simple Fix</h3>
<p>The problem with this is that each of these blocks that accesses an ivar retains self, but the string builder class also retains the dictionaries which in turn retain the blocks. Vicious loop, fortunately with a simple fix.</p>
<p>The simple fix for this is to make sure that the two dictionaries are released when no longer needed. In ARC you force a release by nilling the only reference to them.</p>

<div class="wp_codebox"><table><tr id="p6021113"><td class="code" id="p6021code113"><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>buildString
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// register default handlers</span>
	<span style="color: #002200;">&#91;</span>self _registerTagStartHandlers<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>self _registerTagEndHandlers<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// string building</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// clean up handlers because they retained self</span>
	_tagStartHandlers <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
	_tagEndHandlers <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
	<span style="color: #a61390;">return</span> result;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>That&#8217;s all it takes, boom! Gone are all leaks.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-03-02-um-08.45.42.png"><img class="alignnone size-full wp-image-6026" title="Leaks gone" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-03-02-um-08.45.42.png" alt="" width="842" height="548" /></a></p>
<p>So these &#8220;Leaks&#8221; where no real leaks. They where just the interim objects that made up the NSAttributedString that the string builder produced while building the string from HTML.</p>
<h3>Weak Self</h3>
<p>The more complicated option revolves around having a way to access IVARs and properties without retaining self. Since the blocks are retained by the dictionaries which are retained by the string builder there is no scenario where the block would still live without the string builder still around. So it is perfectly safe to convert self into a weak reference.</p>

<div class="wp_codebox"><table><tr id="p6021114"><td class="code" id="p6021code114"><pre class="objc" style="font-family:monospace;">__weak DTHTMLAttributedStringBuilder <span style="color: #002200;">*</span>weakself <span style="color: #002200;">=</span> self;
&nbsp;
<span style="color: #a61390;">void</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span>someBlock<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">=</span> <span style="color: #002200;">^</span>
<span style="color: #002200;">&#123;</span>
	weakself.someProperty <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;bla&quot;</span>;
	<span style="color: #002200;">&#91;</span>weakself callMethod<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;bar&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>;</pre></td></tr></table></div>

<p>Using this approach you can access all properties and methods of self without causing self to be retained. The final piece of the puzzle is how you can access IVARs for which you didn&#8217;t create a property. Maybe you don&#8217;t want to have the unnecessary Objective-C messaging overhead for just setting a value?</p>
<p>For accessing IVARs Objective-C borrows the arrow operator from C++. This operator is usually used in C++ if you have a pointer to a struct or C++ class and want to access one of the member variables. In Objective-C any IVAR really is just a variable inside a structure too, one that self points to.</p>

<div class="wp_codebox"><table><tr id="p6021115"><td class="code" id="p6021code115"><pre class="objc" style="font-family:monospace;">__weak DTHTMLAttributedStringBuilder <span style="color: #002200;">*</span>weakself <span style="color: #002200;">=</span> self;
&nbsp;
<span style="color: #a61390;">void</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span>someBlock<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">=</span> <span style="color: #002200;">^</span>
<span style="color: #002200;">&#123;</span>
	weakself<span style="color: #002200;">-</span>&gt;ivar <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;bla&quot;</span>;
<span style="color: #002200;">&#125;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// for example:</span>
<span style="color: #a61390;">void</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span>blockquoteBlock<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">=</span> <span style="color: #002200;">^</span>
<span style="color: #002200;">&#123;</span>
	weakself<span style="color: #002200;">-</span>&gt;currentTag.paragraphStyle.firstLineHeadIndent <span style="color: #002200;">=</span> weakself<span style="color: #002200;">-</span>&gt;currentTag.paragraphStyle.headIndent;
	weakself<span style="color: #002200;">-</span>&gt;currentTag.paragraphStyle.paragraphSpacing <span style="color: #002200;">=</span> weakself<span style="color: #002200;">-</span>&gt;defaultFontDescriptor.pointSize;
<span style="color: #002200;">&#125;</span>;</pre></td></tr></table></div>

<p>This is your option number 2, prefixing every property with &#8220;weakself.&#8221; and every IVAR with &#8220;weakself-&gt;&#8221;.</p>
<p>Ugh, so much extra code! I wish there was some option in ARC to tell the compiler not to retain self to be able to avoid all this extra code.</p>
<h3>Conclusion</h3>
<p>When debugging/profiling an application that makes use of blocks be sure to check the &#8220;Cycles&amp;Roots&#8221; view first because those the the easiest to fix. Don&#8217;t waste your time fiddling around with the &#8220;obvious leaks&#8221; and also refrain from blaming Apple.</p>
<p>Of the two methods to avoid a self-retain-cycle I personally prefer the one using less code, i.e. explicitly releasing a container holding onto blocks. But in some situations this might not be an option, so you have to resort to the weakself strategy.</p>
<p>Steve Flack recommends reading Mike Ash&#8217;s <a href="http://mikeash.com/pyblog/friday-qa-2010-04-30-dealing-with-retain-cycles.html">piece on retain cycles</a> and how these behave with <a href="http://www.mikeash.com/pyblog/friday-qa-2011-09-30-automatic-reference-counting.html">ARC</a>.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=6021&amp;md5=c47df2b61f1f0246e5fb2f2a9db41392" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/03/block-retain-loop/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F03%2Fblock-retain-loop%2F&amp;language=en_GB&amp;category=text&amp;title=Block+Retain+Loop&amp;description=I+was+getting+reports+about+DTCoreText+having+leaks.+Not+something+I+like+to+wake+up+to%2C+to+be+honest.+So+I+dived+right+in+with+Instruments+and+the+Leaks+tool....&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Threadsafe Lazy Property Initialization</title>
		<link>http://www.cocoanetics.com/2012/02/threadsafe-lazy-property-initialization/</link>
		<comments>http://www.cocoanetics.com/2012/02/threadsafe-lazy-property-initialization/#comments</comments>
		<pubDate>Wed, 29 Feb 2012 07:51:31 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=6015</guid>
		<description><![CDATA[I was looking for a safe way to initialize a property on individual instances of an object. &#8220;Safe&#8221; as in &#8220;thread-safe&#8221;, because nowadays you never know&#8230; with GCD it could just happen that an object is used from multiple threads concurrently. I felt the need to chronicle the findings here one the different approaches I tried. &#160; In DTCoreText I have a class that represents one line of text. I wanted to protect the method to get the text metrics for this line. @synchronized The classical approach is to use the @synchronized keyword and provide any object to synchronize against. Usually you would use self for this purpose, but you don&#8217;t have to. - &#40;void&#41;calculateMetrics &#123; @synchronized&#40;self&#41; &#123; if &#40;!_didCalculateMetrics&#41; &#123; // do calc &#160; _didCalculateMetrics = YES; &#125; &#125; &#125; These days if you show such code to somebody with at least a passing knowledge of Grand Central Dispatch we will frown and turn his nose on @synchronize. &#8220;Man, synchronize is so much slower than GCD.&#8221; Fiery Robot did a bit of benchmarking which shows that indeed GCD is marginally faster than synchronize, probably because of the more light-weight locking that is available through GCD. This is why David Hoerl changed it to using GCD locking when he updated the project to ARC. GCD Semaphores This adds quite a bit more code as you have to create the locking token (aka semaphore), keep it in an IVAR and release it at the end of the object&#8217;s lifetime. @interface DTCoreTextLayoutLine &#40;&#41; @property &#40;nonatomic, assign&#41; dispatch_semaphore_t layoutLock; @end &#160; @implementation DTCoreTextLayoutLine &#160; - &#40;id&#41;init... &#123; if &#40;&#40;self = &#91;super init&#93;&#41;&#41; &#123; layoutLock = dispatch_semaphore_create&#40;1&#41;; &#125; return self; &#125; &#160; - &#40;void&#41;dealloc &#123; // clean up semaphore dispatch_release&#40;layoutLock&#41;; &#125; &#160; - &#40;void&#41;calculateMetrics &#123; // wait for lock if active dispatch_semaphore_wait&#40;layoutLock, DISPATCH_TIME_FOREVER&#41;; &#160; if &#40;!_didCalculateMetrics&#41; &#123; // do calc &#160; _didCalculateMetrics = YES; &#125; &#160; // release lock dispatch_semaphore_signal&#40;layoutLock&#41;; &#125; This achieves the same degree of safety as the synchronize version, but using GCD and &#8211; marginally &#8211; faster. dispatch_once &#8230; NOT Though there was something about this that bugged me. Previously we learned that if you want something to occur only exactly once you would use dispatch_once. - &#40;void&#41;calculateMetrics &#123; static dispatch_once_t _onceToken; dispatch_once&#40;&#38;_onceToken, ^&#123; // do calc &#160; _didCalculateMetrics = YES; &#125;&#41;; &#125; That looks quaint, but it does not work for the simple reason that static variables are essentially global. Creating the dispatch once token inside the method only creates on token for all instances of this class. So it would calculate the text metrics only for the very first layout line. So my next attempt was to make the once token a private instance variable. That&#8217;s exactly the same as the above example, but instead of static you move the token variable into the curly braces after the implementation. I got even cockier than that. I still had a BOOL to keep track of wether the calc had already been done, so that I don&#8217;t get an overhead of many unnecessary Objective-C function calls. Since the dispatch once token is essentially an integer itself you can also use it in an if. It will be 0 when created and -1 once it was used once. @implementation DTCoreTextLayoutLine &#123; dispatch_once_t _didCalculateMetrics; &#125; &#160; - &#40;void&#41;calculateMetrics &#123; dispatch_once&#40;&#38;_didCalculateMetrics, ^&#123; // do calc &#125;&#41;; &#125; &#160; - &#40;CGFloat&#41;ascent &#123; if &#40;!_didCalculateMetrics&#41; &#123; &#91;self calculateMetrics&#93;; &#125; &#160; return ascent; &#125; This approach looked to me the most elegant involving the least amount of code. So I patted myself on my back and pushed these changes to GitHub for everybody to marvel at my ingenuity. Even some true experts called it &#8220;unconventional&#8221;. BUT &#8230; Unfortunately it&#8217;s not as good as it looks. Somebody had the audacity to read the f&#8217;in manual (RTFM) and point out this sentence to me: The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage is undefined. OH NO! This sentence basically means that you cannot safely use a dispatch once token that is an instance variable or even a regular local variable. Instead it has to be either global outside of your implementation or with the static keyword. The reason for this restriction must be in the way how GCD can access global or static storage in a thread-safe way that it cannot for other types of variables. Maybe something to do with memory locking, that only works properly for these cases. The &#8220;elegant&#8221; method does indeed work, but falls apart in concurrency. There&#8217;s yet another possibility for synchronizing, dispatch_sync. dispatch_sync This is similar to locking semaphores because internally dispatch_sync uses these for synchronizing. Though there is a bit of an advantage of using a sync dispatching over locking. You might end up with a [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/02/threadsafe-lazy-property-initialization/"></g:plusone></div><p>I was looking for a safe way to initialize a property on individual instances of an object. &#8220;Safe&#8221; as in &#8220;thread-safe&#8221;, because nowadays you never know&#8230; with GCD it could just happen that an object is used from multiple threads concurrently.</p>
<p>I felt the need to chronicle the findings here one the different approaches I tried.</p>
<p><span id="more-6015"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>In DTCoreText I have a class that represents one line of text. I wanted to protect the method to get the text metrics for this line. </p>
<h3>@synchronized</h3>
<p>The classical approach is to use the @synchronized keyword and provide any object to synchronize against. Usually you would use self for this purpose, but you don&#8217;t have to.</p>

<div class="wp_codebox"><table><tr id="p6015126"><td class="code" id="p6015code126"><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>calculateMetrics
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">@synchronized</span><span style="color: #002200;">&#40;</span>self<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>_didCalculateMetrics<span style="color: #002200;">&#41;</span>
		<span style="color: #002200;">&#123;</span>
			<span style="color: #11740a; font-style: italic;">// do calc</span>
&nbsp;
			_didCalculateMetrics <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
		<span style="color: #002200;">&#125;</span>
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>These days if you show such code to somebody with at least a passing knowledge of Grand Central Dispatch we will frown and turn his nose on @synchronize. <em>&#8220;Man, synchronize is so much slower than GCD.&#8221;</em></p>
<p><a href="http://www.fieryrobot.com/blog/2010/09/01/synchronization-using-grand-central-dispatch/">Fiery Robot did a bit of benchmarking</a> which shows that indeed GCD is marginally faster than synchronize, probably because of the more light-weight locking that is available through GCD. This is why David Hoerl changed it to using GCD locking when he updated the project to ARC.</p>
<h3>GCD Semaphores</h3>
<p>This adds quite a bit more code as you have to create the locking token (aka semaphore), keep it in an IVAR and release it at the end of the object&#8217;s lifetime.</p>

<div class="wp_codebox"><table><tr id="p6015127"><td class="code" id="p6015code127"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> DTCoreTextLayoutLine <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, assign<span style="color: #002200;">&#41;</span> dispatch_semaphore_t layoutLock;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> DTCoreTextLayoutLine
&nbsp;
<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;">&#40;</span>self <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: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		layoutLock <span style="color: #002200;">=</span> dispatch_semaphore_create<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>dealloc
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// clean up semaphore</span>
	dispatch_release<span style="color: #002200;">&#40;</span>layoutLock<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>calculateMetrics
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// wait for lock if active</span>
	dispatch_semaphore_wait<span style="color: #002200;">&#40;</span>layoutLock, DISPATCH_TIME_FOREVER<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>_didCalculateMetrics<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #11740a; font-style: italic;">// do calc</span>
&nbsp;
		_didCalculateMetrics <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// release lock</span>
	dispatch_semaphore_signal<span style="color: #002200;">&#40;</span>layoutLock<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This achieves the same degree of safety as the synchronize version, but using GCD and &#8211; marginally &#8211; faster.</p>
<h3>dispatch_once &#8230; NOT</h3>
<p>Though there was something about this that bugged me. Previously we learned that if you want something to occur only exactly once you would use dispatch_once.</p>

<div class="wp_codebox"><table><tr id="p6015128"><td class="code" id="p6015code128"><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>calculateMetrics
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">static</span> dispatch_once_t _onceToken;
	dispatch_once<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>_onceToken, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
		<span style="color: #11740a; font-style: italic;">// do calc</span>
&nbsp;
		_didCalculateMetrics <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
	<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>That looks quaint, but it does not work for the simple reason that static variables are essentially global. Creating the dispatch once token inside the method only creates on token for all instances of this class. So it would calculate the text metrics only for the very first layout line. </p>
<p>So my next attempt was to make the once token a private instance variable. That&#8217;s exactly the same as the above example, but instead of static you move the token variable into the curly braces after the implementation.</p>
<p>I got even cockier than that. I still had a BOOL to keep track of wether the calc had already been done, so that I don&#8217;t get an overhead of many unnecessary Objective-C function calls. Since the dispatch once token is essentially an integer itself you can also use it in an if. It will be 0 when created and -1 once it was used once.</p>

<div class="wp_codebox"><table><tr id="p6015129"><td class="code" id="p6015code129"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> DTCoreTextLayoutLine
<span style="color: #002200;">&#123;</span>
	dispatch_once_t _didCalculateMetrics;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>calculateMetrics
<span style="color: #002200;">&#123;</span>
	dispatch_once<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>_didCalculateMetrics, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
		<span style="color: #11740a; font-style: italic;">// do calc</span>
	<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>CGFloat<span style="color: #002200;">&#41;</span>ascent
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>_didCalculateMetrics<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>self calculateMetrics<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #a61390;">return</span> ascent;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This approach looked to me the most elegant involving the least amount of code. So I patted myself on my back and pushed these changes to GitHub for everybody to marvel at my ingenuity. Even some true experts called it &#8220;unconventional&#8221;.</p>
<p>BUT &#8230;</p>
<p>Unfortunately it&#8217;s not as good as it looks. Somebody had the audacity to <a href="https://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html">read the f&#8217;in manual</a> (RTFM) and point out this sentence to me:</p>
<blockquote><p>The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage is undefined.</p></blockquote>
<p>OH NO! This sentence basically means that you cannot safely use a dispatch once token that is an instance variable or even a regular local variable. Instead it has to be either global outside of your implementation or with the static keyword.</p>
<p>The reason for this restriction must be in the way how GCD can access global or static storage in a thread-safe way that it cannot for other types of variables. Maybe something to do with memory locking, that only works properly for these cases.</p>
<p>The &#8220;elegant&#8221; method does indeed work, but falls apart in concurrency.</p>
<p>There&#8217;s yet another possibility for synchronizing, dispatch_sync. </p>
<h3>dispatch_sync</h3>
<p>This is similar to locking semaphores because internally dispatch_sync uses these for synchronizing. Though there is a bit of an advantage of using a sync dispatching over locking. You might end up with a dead lock if a lock-protected section tries to wait for the lock as well.</p>

<div class="wp_codebox"><table><tr id="p6015130"><td class="code" id="p6015code130"><pre class="objc" style="font-family:monospace;">&nbsp;
<span style="color: #a61390;">@implementation</span> DTCoreTextLayoutLine
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">BOOL</span> _didCalculateMetrics;
	dispatch_queue_t _syncQueue;
<span style="color: #002200;">&#125;</span>
&nbsp;
<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;">&#40;</span>self <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: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #11740a; font-style: italic;">// get a global queue</span>
		_syncQueue <span style="color: #002200;">=</span> dispatch_get_global_queue<span style="color: #002200;">&#40;</span>DISPATCH_QUEUE_PRIORITY_DEFAULT, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>calculateMetrics
<span style="color: #002200;">&#123;</span>
	dispatch_sync<span style="color: #002200;">&#40;</span>_syncQueue, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>_didCalculateMetrics<span style="color: #002200;">&#41;</span>
		<span style="color: #002200;">&#123;</span>
			<span style="color: #11740a; font-style: italic;">// do calc</span>
&nbsp;
			_didCalculateMetrics <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
		<span style="color: #002200;">&#125;</span>
	<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>The previous example uses a global queue (available in low, default and high priority) and as such does not need to worry about retaining or releasing it, as these live as long as your app does.</p>
<p>Again the <a href="https://developer.apple.com/library/ios/#DOCUMENTATION/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html">RTFM</a> contains a suggestion for us:</p>
<blockquote><p>Although dispatch queues are reference-counted objects, you do not need to retain and release the global concurrent queues. Because they are global to your application, retain and release calls for these queues are ignored. Therefore, you do not need to store references to these queues. You can just call the dispatch_get_global_queue function whenever you need a reference to one of them.</p></blockquote>
<p>But personally I&#8217;d rather set up the reference to the queue I want to use for synching in an IVAR because when I can be sure to have the exact same queue available in different methods of the same object. If you are doing some very tight and extensive looping then the overhead of unnecessary function calls can pile up.</p>
<h3>Conclusion</h3>
<p>It is unfortunate that dispatch_once does not work in the context of lazy property initialization. For this scenario we have 3 options at our disposal. The original synchronize, locking with semaphores and sync dispatching. </p>
<p>One use was intentionally omitted from this: dispatch_async. The reason being that the above mentioned benchmark showed it as substantially slower than the other variants because of the system having to copy the blocks to the heap. Sync dispatching can keep the block on the stack and execute it right away.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=6015&amp;md5=3ab3c13c04956d0852b94beb9fb03683" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/02/threadsafe-lazy-property-initialization/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F02%2Fthreadsafe-lazy-property-initialization%2F&amp;language=en_GB&amp;category=text&amp;title=Threadsafe+Lazy+Property+Initialization&amp;description=I+was+looking+for+a+safe+way+to+initialize+a+property+on+individual+instances+of+an+object.+%26%238220%3BSafe%26%238221%3B+as+in+%26%238220%3Bthread-safe%26%238221%3B%2C+because+nowadays+you+never+know%26%238230%3B+with+GCD+it+could...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Caching Caches</title>
		<link>http://www.cocoanetics.com/2012/02/caching-caches/</link>
		<comments>http://www.cocoanetics.com/2012/02/caching-caches/#comments</comments>
		<pubDate>Thu, 16 Feb 2012 07:54:38 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5966</guid>
		<description><![CDATA[While doing some performance tuning on the iCatalog.framework I stumbled upon a method of about 7 statements where a single line was responsible for more than a third of all CPU time. This basically was only getting the path to the app&#8217;s Library/Caches folder. By itself this statement looks very innocent and I had it in about a dozen places all around the app. But it turns out that if you calling it hundreds or thousands of times then the time it takes to search for the Caches (and Documents) path sums up enormously. Interestingly it does not seem like Apple implemented any caching for them so they seem to use around the same time all the time. But these values are prime candidates for caching because they won&#8217;t change while your app is running. Also the objc function call to get a cached version of the paths is several orders of magnitude faster than determining it in the first place. &#160; This is what I saw in Instruments: Granted, in most apps you would probably never notice a difference, but if you work with the documents or caches folders frequently in loops and/or many places then this is for you. I added two category methods to my DTFoundation project to add caching. @implementation NSString &#40;DTPaths&#41; &#160; + &#40;NSString *&#41;cachesPath &#123; static dispatch_once_t onceToken; static NSString *cachedPath; &#160; dispatch_once&#40;&#38;onceToken, ^&#123; cachedPath = &#91;NSSearchPathForDirectoriesInDomains&#40;NSCachesDirectory, NSUserDomainMask, YES&#41; lastObject&#93;; &#125;&#41;; &#160; return cachedPath; &#125; &#160; + &#40;NSString *&#41;documentsPath &#123; static dispatch_once_t onceToken; static NSString *cachedPath; &#160; dispatch_once&#40;&#38;onceToken, ^&#123; cachedPath = &#91;NSSearchPathForDirectoriesInDomains&#40;NSDocumentDirectory, NSUserDomainMask, YES&#41; lastObject&#93;; &#125;&#41;; &#160; return cachedPath; &#125; @end I introduced this pattern using a &#8220;onceToken&#8221; previously and it proves to be a boon. So you should learn it by heart. You create a static dispatch once token as well as a static pointer to something that you want to cache. Then you wrap the creation of the item in a dispatch_once. Et voila! Before GCD we would have done this sort of caching with a if (!cachedPath) but the GCD-way has the added benefit of being thread-safe. As a general rule of thumb you should cache everything that is expensive to get (calculation or via network) and does not change much. If it is just a single pointer, like an NSString * the above approach works marvelously. If you want to see how this can be combined with the use of NSCache for multiple values, check out &#8230; OMG, I was about to write &#8220;checkout the DTFontDescriptor class in DTCoreText&#8221; as a shining example of how to initialize a font cache. But here&#8217;s what I found: + &#40;NSCache *&#41;fontCache &#123; if &#40;!_fontCache&#41; &#123; _fontCache = &#91;&#91;NSCache alloc&#93; init&#93;; &#125; &#160; return _fontCache; &#125; This is exactly the non-GCD-way that I alluded to above. This hasn&#8217;t been a problem so far because all calls to it would have come from the same thread, but while we are at its a great exercise to show that we have properly inhaled the knowledge imparted upon us above. + &#40;NSCache *&#41;fontCache &#123; static dispatch_once_t onceToken; &#160; dispatch_once&#40;&#38;onceToken, ^&#123; _fontCache = &#91;&#91;NSCache alloc&#93; init&#93;; &#125;&#41;; &#160; return _fontCache; &#125; Ah, much better. Works just like before, but now thread-safe. There is one riddle that I stumbled up I was not able to explain. In the same file DTFontDescriptor I also tried to adjust the second lookup table fontOverrides in the same fashion, but when trying to run the Demo it stalls somehow deadlocked. Could it be that the current way of using semaphores to synchronizing interferes with the dispatch_once? Comment below if you know how to fix that&#8230;]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/02/caching-caches/"></g:plusone></div><p>While doing some performance tuning on the <a title="iCatalog.framework brings Digital Catalogs to Life on iPad" href="http://www.cocoanetics.com/2010/10/icatalog-framework-brings-digital-catalogs-to-life-on-ipad/">iCatalog.framework</a> I stumbled upon a method of about 7 statements where a single line was responsible for more than a third of all CPU time.</p>
<p>This basically was only getting the path to the app&#8217;s Library/Caches folder. By itself this statement looks very innocent and I had it in about a dozen places all around the app. But it turns out that if you calling it hundreds or thousands of times then the time it takes to search for the Caches (and Documents) path sums up enormously.</p>
<p>Interestingly it does not seem like Apple implemented any caching for them so they seem to use around the same time all the time. But these values are prime candidates for caching because they won&#8217;t change while your app is running. Also the objc function call to get a cached version of the paths is several orders of magnitude faster than determining it in the first place.</p>
<p><span id="more-5966"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>This is what I saw in Instruments:</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-02-16-um-11.58.44-AM2.png"><img src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-02-16-um-11.58.44-AM2.png" alt="" title="Instruments" width="720" height="169" class="alignnone size-full wp-image-5976" /></a></p>
<p>Granted, in most apps you would probably never notice a difference, but if you work with the documents or caches folders frequently in loops and/or many places then this is for you.</p>
<p>I added two category methods to my DTFoundation project to add caching.</p>

<div class="wp_codebox"><table><tr id="p5966139"><td class="code" id="p5966code139"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">&#40;</span>DTPaths<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>cachesPath
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">static</span> dispatch_once_t onceToken;
	<span style="color: #a61390;">static</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>cachedPath;
&nbsp;
	dispatch_once<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>onceToken, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
		cachedPath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>NSSearchPathForDirectoriesInDomains<span style="color: #002200;">&#40;</span>NSCachesDirectory, NSUserDomainMask, <span style="color: #a61390;">YES</span><span style="color: #002200;">&#41;</span> lastObject<span style="color: #002200;">&#93;</span>;	
	<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">return</span> cachedPath;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>documentsPath
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">static</span> dispatch_once_t onceToken;
	<span style="color: #a61390;">static</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>cachedPath;
&nbsp;
	dispatch_once<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>onceToken, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
		cachedPath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>NSSearchPathForDirectoriesInDomains<span style="color: #002200;">&#40;</span>NSDocumentDirectory, NSUserDomainMask, <span style="color: #a61390;">YES</span><span style="color: #002200;">&#41;</span> lastObject<span style="color: #002200;">&#93;</span>;	
	<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">return</span> cachedPath;
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>I introduced this pattern using a &#8220;onceToken&#8221; <a title="Fast Folder Nuking on iOS" href="http://www.cocoanetics.com/2012/02/fast-folder-nuking-on-ios/">previously</a> and it proves to be a boon. So you should learn it by heart. You create a static dispatch once token as well as a static pointer to something that you want to cache. Then you wrap the creation of the item in a dispatch_once. Et voila!</p>
<p>Before GCD we would have done this sort of caching with a if (!cachedPath) but the GCD-way has the added benefit of being thread-safe.</p>
<p>As a general rule of thumb you should cache everything that is expensive to get (calculation or via network) and does not change much. If it is just a single pointer, like an NSString * the above approach works marvelously. If you want to see how this can be combined with the use of NSCache for multiple values, check out &#8230;</p>
<p>OMG, I was about to write &#8220;checkout the DTFontDescriptor class in DTCoreText&#8221; as a shining example of how to initialize a font cache. But here&#8217;s what I found:</p>

<div class="wp_codebox"><table><tr id="p5966140"><td class="code" id="p5966code140"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span>NSCache <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>fontCache
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>_fontCache<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		_fontCache <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSCache alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #a61390;">return</span> _fontCache;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This is exactly the non-GCD-way that I alluded to above. This hasn&#8217;t been a problem so far because all calls to it would have come from the same thread, but while we are at its a great exercise to show that we have properly inhaled the knowledge imparted upon us above.</p>

<div class="wp_codebox"><table><tr id="p5966141"><td class="code" id="p5966code141"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span>NSCache <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>fontCache
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">static</span> dispatch_once_t onceToken;
&nbsp;
	dispatch_once<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>onceToken, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
		_fontCache <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSCache alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">return</span> _fontCache;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Ah, much better. Works just like before, but now thread-safe.</p>
<p>There is one riddle that I stumbled up I was not able to explain. In the same file DTFontDescriptor I also tried to adjust the second lookup table fontOverrides in the same fashion, but when trying to run the Demo it stalls somehow deadlocked. Could it be that the current way of using semaphores to synchronizing interferes with the dispatch_once?</p>
<p>Comment below if you know how to fix that&#8230;</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5966&amp;md5=337c56728c37e10252ce1b0b44a81846" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/02/caching-caches/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F02%2Fcaching-caches%2F&amp;language=en_GB&amp;category=text&amp;title=Caching+Caches&amp;description=While+doing+some+performance+tuning+on+the+iCatalog.framework+I+stumbled+upon+a+method+of+about+7+statements+where+a+single+line+was+responsible+for+more+than+a+third+of+all...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Decompressing Files into Memory</title>
		<link>http://www.cocoanetics.com/2012/02/decompressing-files-into-memory/</link>
		<comments>http://www.cocoanetics.com/2012/02/decompressing-files-into-memory/#comments</comments>
		<pubDate>Tue, 14 Feb 2012 08:57:39 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5957</guid>
		<description><![CDATA[As a hobby project I am working on uncovering hidden treasures that exist on all your iOS devices. Hidden, because there is no Objective-C API for them, Existing, because Apple includes a great deal of open source libraries in iOS, compiled as a dynamic library. What items exist you can see if you check out what dylibs are there to be seen in &#8220;Link Binary with Libraries&#8221;. Most entries beginning with lib and ending with dylib can be used. Some people have reported getting rejected for adding the static variants of libraries like libxslt or libarchive, but that&#8217;s probably because Apple sees these symbols as duplicate to the ones contained in the dynamic libraries. We previously looked at libxml2 for parsing HTML (and part 2), today we&#8217;ll familiarize ourselves with zlib for decompressing .gz and .zip files. &#160; The first time I came in contact with decompressing files was on my MyAppSales open source project. There I was scraping iTunes Connect and the downloaded files were compressed in ZIP format. The new unofficial iTunes Connect API compresses the daily and weekly reports in GZIP format, which no longer works. This is why I set out to find a solution that works for both. There are several compression schemes out there, but the most prevalent two are PKZIP (as popularized by WinZIP) and GZIP (as in GNU Zip). The former is a wrapper around the latter. GZIP only supports a single file, whereas PKZIP adds a special file header that has an index of the included files with pointers to the locations of the corresponding GZIP chunks. In Memory Decompression: GZIP zlib by itself can only deal with zlib-compressed streams (&#8220;deflated&#8221;), GZIP in turn adds a minimal header for this deflated content. Decompressing streams with pure zlib-compression or zlib+GZIP header is relatively straightforward. Here&#8217;s the method I gleaned (and cleaned up) from CocoaDev&#8217;s NSData category. NSUInteger dataLength = &#91;_data length&#93;; NSUInteger halfLength = dataLength / 2; &#160; NSMutableData *decompressed = &#91;NSMutableData dataWithLength: dataLength + halfLength&#93;; BOOL done = NO; int status; &#160; z_stream strm; strm.next_in = &#40;Bytef *&#41;&#91;_data bytes&#93;; strm.avail_in = &#40;uInt&#41;dataLength; strm.total_out = 0; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; &#160; // inflateInit2 knows how to deal with gzip format if &#40;inflateInit2&#40;&#38;strm, &#40;15+32&#41;&#41; != Z_OK&#41; &#123; return; &#125; &#160; while &#40;!done&#41; &#123; // extend decompressed if too short if &#40;strm.total_out &#62;= &#91;decompressed length&#93;&#41; &#123; &#91;decompressed increaseLengthBy: halfLength&#93;; &#125; &#160; strm.next_out = &#91;decompressed mutableBytes&#93; + strm.total_out; strm.avail_out = &#40;uInt&#41;&#91;decompressed length&#93; - &#40;uInt&#41;strm.total_out; &#160; // Inflate another chunk. status = inflate &#40;&#38;strm, Z_SYNC_FLUSH&#41;; &#160; if &#40;status == Z_STREAM_END&#41; &#123; done = YES; &#125; else if &#40;status != Z_OK&#41; &#123; break; &#125; &#125; &#160; if &#40;inflateEnd &#40;&#38;strm&#41; != Z_OK &#124;&#124; !done&#41; &#123; return; &#125; &#160; // set actual length &#91;decompressed setLength:strm.total_out&#93;; This method works by setting up a zstream struct with a pointer and length to the data bytes of the file. Then it initializes the decompressor with inflateInit2. The trailing 2 is important in this function as this is the version that knows how to deal with the GZIP header. The decompression occurs by calling inflate until this returns Z_STREAM_END. Finally the decompressor is freed up by calling inflateEnd. I liked this approach because it keeps adding half of the compressed data size to the output mutable data object. This is way more efficient than constantly adding each decompressed chunk to the data forcing it to constantly reallocate larger bits of memory and copying the contents. At the end it uses setLength to specify the actual length of data. In Memory Decompression: PKZIP You can tell a GZIP and PKZIP file apart by inspecting the first two bytes of it. If these are &#8216;PK&#8217; then you have a ZIP file. PKZIP adds a special header so that multiple GZIPped files can peacefully coexist in a single .ZIP file. Dealing with this header is quite tedious so people are happy to use Minizip. This is another C-library that wraps this complexity up. If you take it as it is there are some compiler warnings, so &#8211; lazy me &#8211; I used the cleaned up version by Sam Soffes. The Objective-C versions of decompressing PKZIP seem all to be more or less based on ZipArchive project by &#8220;Aish&#8221;. You can tell that this is the case because they generally contain the same bug dealing with the file date of the zipped files. If you find a reference to Jan 1st 1980 in there, you know what I mean. The &#8211; simplified &#8211; structure of dealing with a PKZIP in memory is this: unsigned char buffer&#91;BUFFER_SIZE&#93; = &#123;0&#125;; &#160; // open the file for unzipping unzFile _unzFile = unzOpen&#40;&#40;const char *&#41;&#91;_path UTF8String&#93;&#41;; &#160; // return if failed if &#40;!_unzFile&#41; &#123; return; &#125; &#160; // get file info unz_global_info globalInfo = &#123;0&#125;; &#160; if &#40;!unzGetGlobalInfo&#40;_unzFile, &#38;globalInfo &#41;==UNZ_OK [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/02/decompressing-files-into-memory/"></g:plusone></div><p>As a hobby project I am working on uncovering hidden treasures that exist on all your iOS devices. Hidden, because there is no Objective-C API for them, Existing, because Apple includes a great deal of open source libraries in iOS, compiled as a dynamic library.</p>
<p>What items exist you can see if you check out what dylibs are there to be seen in &#8220;Link Binary with Libraries&#8221;. Most entries beginning with lib and ending with dylib can be used. Some people have reported getting rejected for adding the static variants of libraries like libxslt or libarchive, but that&#8217;s probably because Apple sees these symbols as duplicate to the ones contained in the dynamic libraries.</p>
<p>We previously looked at <a title="Taming HTML Parsing with libxml (1)" href="http://www.cocoanetics.com/2011/09/taming-html-parsing-with-libxml-1/">libxml2 for parsing HTML</a> (and <a title="Taming HTML Parsing with libxml (2)" href="http://www.cocoanetics.com/2012/01/taming-html-parsing-with-libxml-2/">part 2</a>), today we&#8217;ll familiarize ourselves with zlib for decompressing .gz and .zip files.</p>
<p><span id="more-5957"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>The first time I came in contact with decompressing files was on my <a href="https://github.com/Cocoanetics/MyAppSales">MyAppSales open source project</a>. There I was scraping iTunes Connect and the downloaded files were compressed in ZIP format. The new unofficial iTunes Connect API compresses the daily and weekly reports in GZIP format, which no longer works. This is why I set out to find a solution that works for both.</p>
<p>There are several compression schemes out there, but the most prevalent two are PKZIP (as popularized by WinZIP) and GZIP (as in GNU Zip). The former is a wrapper around the latter. GZIP only supports a single file, whereas PKZIP adds a special file header that has an index of the included files with pointers to the locations of the corresponding GZIP chunks.</p>
<h3>In Memory Decompression: GZIP</h3>
<p>zlib by itself can only deal with zlib-compressed streams (&#8220;deflated&#8221;), GZIP in turn adds a minimal header for this deflated content. Decompressing streams with pure zlib-compression or zlib+GZIP header is relatively straightforward. Here&#8217;s the method I gleaned (and cleaned up) from <a href="http://www.cocoadev.com/index.pl?NSDataCategory">CocoaDev&#8217;s NSData category</a>.</p>

<div class="wp_codebox"><table><tr id="p5957148"><td class="code" id="p5957code148"><pre class="objc" style="font-family:monospace;">NSUInteger dataLength <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>_data length<span style="color: #002200;">&#93;</span>;
NSUInteger halfLength <span style="color: #002200;">=</span> dataLength <span style="color: #002200;">/</span> <span style="color: #2400d9;">2</span>;
&nbsp;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableData_Class/"><span style="color: #400080;">NSMutableData</span></a> <span style="color: #002200;">*</span>decompressed <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableData_Class/"><span style="color: #400080;">NSMutableData</span></a> dataWithLength<span style="color: #002200;">:</span> dataLength <span style="color: #002200;">+</span> halfLength<span style="color: #002200;">&#93;</span>;
<span style="color: #a61390;">BOOL</span> done <span style="color: #002200;">=</span> <span style="color: #a61390;">NO</span>;
<span style="color: #a61390;">int</span> status;
&nbsp;
z_stream strm;
strm.next_in <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>Bytef <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span>_data bytes<span style="color: #002200;">&#93;</span>;
strm.avail_in <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>uInt<span style="color: #002200;">&#41;</span>dataLength;
strm.total_out <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>;
strm.zalloc <span style="color: #002200;">=</span> Z_NULL;
strm.zfree <span style="color: #002200;">=</span> Z_NULL;
&nbsp;
<span style="color: #11740a; font-style: italic;">// inflateInit2 knows how to deal with gzip format</span>
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>inflateInit2<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>strm, <span style="color: #002200;">&#40;</span><span style="color: #2400d9;">15</span><span style="color: #002200;">+</span><span style="color: #2400d9;">32</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">!=</span> Z_OK<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">return</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">while</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>done<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// extend decompressed if too short</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>strm.total_out &gt;<span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>decompressed length<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>decompressed increaseLengthBy<span style="color: #002200;">:</span> halfLength<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	strm.next_out <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>decompressed mutableBytes<span style="color: #002200;">&#93;</span> <span style="color: #002200;">+</span> strm.total_out;
	strm.avail_out <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>uInt<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span>decompressed length<span style="color: #002200;">&#93;</span> <span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>uInt<span style="color: #002200;">&#41;</span>strm.total_out;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// Inflate another chunk.</span>
	status <span style="color: #002200;">=</span> inflate <span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>strm, Z_SYNC_FLUSH<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>status <span style="color: #002200;">==</span> Z_STREAM_END<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		done <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</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>status <span style="color: #002200;">!=</span> Z_OK<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">break</span>;	
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>inflateEnd <span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>strm<span style="color: #002200;">&#41;</span> <span style="color: #002200;">!=</span> Z_OK || <span style="color: #002200;">!</span>done<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">return</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// set actual length</span>
<span style="color: #002200;">&#91;</span>decompressed setLength<span style="color: #002200;">:</span>strm.total_out<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>This method works by setting up a zstream struct with a pointer and length to the data bytes of the file. Then it initializes the decompressor with inflateInit2. The trailing 2 is important in this function as this is the version that knows how to deal with the GZIP header. The decompression occurs by calling inflate until this returns Z_STREAM_END. Finally the decompressor is freed up by calling inflateEnd.</p>
<p>I liked this approach because it keeps adding half of the compressed data size to the output mutable data object. This is way more efficient than constantly adding each decompressed chunk to the data forcing it to constantly reallocate larger bits of memory and copying the contents. At the end it uses setLength to specify the actual length of data.</p>
<h3>In Memory Decompression: PKZIP</h3>
<p>You can tell a GZIP and PKZIP file apart by inspecting the first two bytes of it. If these are &#8216;PK&#8217; then you have a ZIP file. </p>
<p>PKZIP adds a special header so that multiple GZIPped files can peacefully coexist in a single .ZIP file. Dealing with this header is quite tedious so people are happy to use <a href="http://www.winimage.com/zLibDll/minizip.html">Minizip</a>. This is another C-library that wraps this complexity up. If you take it as it is there are some compiler warnings, so &#8211; lazy me &#8211; I used the <a href="https://github.com/samsoffes/ssziparchive/tree/master/minizip">cleaned up version by Sam Soffes</a>.</p>
<p>The Objective-C versions of decompressing PKZIP seem all to be more or less based on <a href="http://code.google.com/p/ziparchive/">ZipArchive</a> project by &#8220;Aish&#8221;. You can tell that this is the case because they generally contain the same bug dealing with the file date of the zipped files. If you find a reference to Jan 1st 1980 in there, you know what I mean.</p>
<p>The &#8211; simplified &#8211; structure of dealing with a PKZIP in memory is this:</p>

<div class="wp_codebox"><table><tr id="p5957149"><td class="code" id="p5957code149"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">unsigned</span> <span style="color: #a61390;">char</span> buffer<span style="color: #002200;">&#91;</span>BUFFER_SIZE<span style="color: #002200;">&#93;</span> <span style="color: #002200;">=</span> <span style="color: #002200;">&#123;</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#125;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// open the file for unzipping</span>
unzFile _unzFile <span style="color: #002200;">=</span> unzOpen<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">const</span> <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span>_path UTF8String<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// return if failed</span>
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>_unzFile<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">return</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// get file info</span>
unz_global_info  globalInfo <span style="color: #002200;">=</span> <span style="color: #002200;">&#123;</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#125;</span>;
&nbsp;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>unzGetGlobalInfo<span style="color: #002200;">&#40;</span>_unzFile, <span style="color: #002200;">&amp;</span>globalInfo <span style="color: #002200;">&#41;</span><span style="color: #002200;">==</span>UNZ_OK <span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// there's a problem</span>
	<span style="color: #a61390;">return</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>unzGoToFirstFile<span style="color: #002200;">&#40;</span>_unzFile<span style="color: #002200;">&#41;</span><span style="color: #002200;">!=</span>UNZ_OK<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// unable to go to first file</span>
	<span style="color: #a61390;">return</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// enum block can stop loop</span>
<span style="color: #a61390;">BOOL</span> shouldStop <span style="color: #002200;">=</span> <span style="color: #a61390;">NO</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// iterate through all files</span>
<span style="color: #a61390;">do</span> 
<span style="color: #002200;">&#123;</span>
	unz_file_info zipInfo <span style="color: #002200;">=</span><span style="color: #002200;">&#123;</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#125;</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>unzOpenCurrentFile<span style="color: #002200;">&#40;</span>_unzFile<span style="color: #002200;">&#41;</span> <span style="color: #002200;">!=</span> UNZ_OK<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #11740a; font-style: italic;">// error uncompressing this file</span>
		<span style="color: #a61390;">return</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// first call for file info so that we know length of file name</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>unzGetCurrentFileInfo<span style="color: #002200;">&#40;</span>_unzFile, <span style="color: #002200;">&amp;</span>zipInfo, <span style="color: #a61390;">NULL</span>, <span style="color: #2400d9;">0</span>, <span style="color: #a61390;">NULL</span>, <span style="color: #2400d9;">0</span>, <span style="color: #a61390;">NULL</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">!=</span> UNZ_OK<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #11740a; font-style: italic;">// cannot get file info</span>
		unzCloseCurrentFile<span style="color: #002200;">&#40;</span>_unzFile<span style="color: #002200;">&#41;</span>;
		<span style="color: #a61390;">return</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// reserve space for file name</span>
	<span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>fileNameC <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">char</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span><a href="http://www.opengroup.org/onlinepubs/009695399/functions/malloc.html"><span style="color: #a61390;">malloc</span></a><span style="color: #002200;">&#40;</span>zipInfo.size_filename<span style="color: #002200;">+</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// second call to get actual file name	</span>
	unzGetCurrentFileInfo<span style="color: #002200;">&#40;</span>_unzFile, <span style="color: #002200;">&amp;</span>zipInfo, fileNameC, zipInfo.size_filename <span style="color: #002200;">+</span> <span style="color: #2400d9;">1</span>, <span style="color: #a61390;">NULL</span>, <span style="color: #2400d9;">0</span>, <span style="color: #a61390;">NULL</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
	fileNameC<span style="color: #002200;">&#91;</span>zipInfo.size_filename<span style="color: #002200;">&#93;</span> <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">'<span style="color: #2400d9;">\0</span>'</span>;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>fileName <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> stringWithUTF8String<span style="color: #002200;">:</span>fileNameC<span style="color: #002200;">&#93;</span>;
	<a href="http://www.opengroup.org/onlinepubs/009695399/functions/free.html"><span style="color: #a61390;">free</span></a><span style="color: #002200;">&#40;</span>fileNameC<span style="color: #002200;">&#41;</span>;
&nbsp;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableData_Class/"><span style="color: #400080;">NSMutableData</span></a> <span style="color: #002200;">*</span>tmpData <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableData_Class/"><span style="color: #400080;">NSMutableData</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #a61390;">int</span> readBytes;
	<span style="color: #a61390;">while</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>readBytes <span style="color: #002200;">=</span> unzReadCurrentFile<span style="color: #002200;">&#40;</span>_unzFile, buffer, BUFFER_SIZE<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> &gt; <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>tmpData appendBytes<span style="color: #002200;">:</span>buffer length<span style="color: #002200;">:</span>readBytes<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// decompressed file now in tmpData, name in fileName</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// close the current file</span>
	unzCloseCurrentFile<span style="color: #002200;">&#40;</span>_unzFile<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">while</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>shouldStop <span style="color: #002200;">&amp;&amp;</span> unzGoToNextFile<span style="color: #002200;">&#40;</span>_unzFile <span style="color: #002200;">&#41;</span><span style="color: #002200;">==</span>UNZ_OK<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>Now about these file dates &#8230; For some unfortunate historical reasons Microsoft didn&#8217;t think to include time zone support in DOS file dates. We will never now why. There are two ways how a file date can be represented in PKZIPped files. The zipInfo header struct both contains a dosdate value as well as a tmu_date struct. The spec states that if the dosdate is 0 then the tmu_date is to be used which has individual fields for hour, min, sec, day, month and year. But no time zone either.</p>
<p>Now the bug I alluded to above is to assume that &#8211; like on Unix &#8211; the dosdate is a time stamp, a number of seconds since a reference date. The implementations that get this wrong just assume that the dosdate is a number of seconds since beginning of 1980. The problem is that there might still be some files out there that ONLY use the dosdate, so we cannot just ignore that and go with the tmu_date.</p>
<p>I found the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms724247(v=vs.85).aspx">spec for the dos date</a> hidden deep in Microsoft&#8217;s web. It simply compresses all the date parts into 2 bytes, using only as many bits as necessary for each value. And to save one bit on the seconds these are divided by 2.</p>

<div class="wp_codebox"><table><tr id="p5957150"><td class="code" id="p5957code150"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">long</span> l <span style="color: #002200;">=</span> <span style="color: #2400d9;">1078768689</span>; <span style="color: #11740a; font-style: italic;">// a dosdate</span>
&nbsp;
<span style="color: #a61390;">int</span> year <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>l&gt;&gt;<span style="color: #2400d9;">25</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&amp;</span><span style="color: #2400d9;">127</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">+</span> <span style="color: #2400d9;">1980</span>;  <span style="color: #11740a; font-style: italic;">// 7 bits</span>
<span style="color: #a61390;">int</span> month <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>l&gt;&gt;<span style="color: #2400d9;">21</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&amp;</span><span style="color: #2400d9;">15</span>;  <span style="color: #11740a; font-style: italic;">// 4 bits</span>
<span style="color: #a61390;">int</span> day <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>l&gt;&gt;<span style="color: #2400d9;">16</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&amp;</span><span style="color: #2400d9;">31</span>; <span style="color: #11740a; font-style: italic;">// 5 bits</span>
<span style="color: #a61390;">int</span> hour <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>l&gt;&gt;<span style="color: #2400d9;">11</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&amp;</span><span style="color: #2400d9;">31</span>; <span style="color: #11740a; font-style: italic;">// 5 bits</span>
<span style="color: #a61390;">int</span> minute <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>l&gt;&gt;<span style="color: #2400d9;">5</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&amp;</span><span style="color: #2400d9;">63</span>;	<span style="color: #11740a; font-style: italic;">// 6 bits	</span>
<span style="color: #a61390;">int</span> second <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>l<span style="color: #002200;">&amp;</span><span style="color: #2400d9;">31</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">*</span> <span style="color: #2400d9;">2</span>;  <span style="color: #11740a; font-style: italic;">// 5 bits</span></pre></td></tr></table></div>

<p>Crazy, isn&#8217;t it? I can see how somebody might have assumed that this is a number of seconds since 1980 as the year value is at the highest order bits. </p>
<p>If the dosdate is 0 then you can trust the tmu_date to contain the local time where the ZIP file was created. But I&#8217;ll leave this exercise to you. Just one hint: January is month 0.</p>
<p>We usually don&#8217;t care about getting the exact file stamps correct. If you do you need to either save the time zone inside the ZIP file as well, possibly as a plain text file. Or alternatively if you know that the files came from a certain server you can assume this time zone.</p>
<p>PKZIP also supports encrypting files with a password. If you never deal with thus encrypted files you can disable crypt support by defining NOCRYPT and NOUNCRYPT. This omits the crypt code from the compiled binary. The header minizip/crypt.h claims:</p>
<blockquote><p>The encryption/decryption parts of this source code (as opposed to the non-echoing password parts) were originally written in Europe.  The whole source package can be freely distributed, including from the USA. (Prior to January 2000, re-export from the US was a violation of US law.) </p></blockquote>
<p>But then again, the original encryption is relatively weak, several cracking tools exist which can <a href="http://www.unix-ag.uni-kl.de/~conrad/krypto/pkcrack.html">brute force</a> it. There are two stronger encryption schemes introduced by WinZip and PKWare PKZip which are not even supported by minizip. So you are probably safer if you just omit the encrypting parts if you don&#8217;t want to jump hoops presented by Apple or the US Government or face the grief of not-supported encryption schemes.</p>
<h3>Conclusion</h3>
<p>The source code featured in this article is available as part of <a href="https://github.com/Cocoanetics/DTFoundation">DTFoundation</a>, check out the DTZipArchive class there.</p>
<p>There isn&#8217;t really much there once you gotten used calling C functions. And unfortunately documentation or tutorials on the subject matter are pretty hard to come by. But thankfully &#8211; almost always &#8211; somebody has blazed the trail and provided something that we can use to pattern our approach after.</p>
<p>Especially in Unix circles there is a third decompression scheme that I neglected to mention: tar.gz. This works around the single-file limitation of GZIP by concatenating the files first and then deflating them. The methods to deal with these files are available in libarchive.dylib, available in the dylibs I mentioned above. I am looking for somebody who can confirm that this is indeed app-store-legal before I add support for tar.gz to DTZipArchive.</p>
<p>I would also be interested to hear from somebody using minizip in app store apps and whether the crypt code was omitted and/or the encryption exporting process was required.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5957&amp;md5=25b63168c3bb1e988a172701dfd4ce6e" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/02/decompressing-files-into-memory/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F02%2Fdecompressing-files-into-memory%2F&amp;language=en_GB&amp;category=text&amp;title=Decompressing+Files+into+Memory&amp;description=As+a+hobby+project+I+am+working+on+uncovering+hidden+treasures+that+exist+on+all+your+iOS+devices.+Hidden%2C+because+there+is+no+Objective-C+API+for+them%2C+Existing%2C+because+Apple...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Fast Folder Nuking on iOS</title>
		<link>http://www.cocoanetics.com/2012/02/fast-folder-nuking-on-ios/</link>
		<comments>http://www.cocoanetics.com/2012/02/fast-folder-nuking-on-ios/#comments</comments>
		<pubDate>Sat, 11 Feb 2012 08:17:02 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5943</guid>
		<description><![CDATA[I got a strange bug report last week for iCatalog. Deleting of outdated catalogs takes too long, if we couldn&#8217;t show a HUD with a spinner while the deletion occurs. That was definitely one of these HUUUUU?! moments. I always thought that file deletion is instant on Unix since only an entry in a file table needs to be removed. I grabbed an iPad 1 and deleted a 160 MB catalog. Only to find that the whole deletion &#8211; a simple NSFileManager removeItemAtPath &#8211; took 50 seconds. Uhm, no that is far from ideal to be blocking the main thread and interface for that long. I played around a bit and over the course of the day, with some great help from several GCD experts on twitter, I pieced together a solution that might interest you if you ever have to delete large amounts of files in an instant. Before Cocoa, on Carbon, OSX offered a method called FSPathMoveObjectToTrashAsync, this is sort of the equivalent for iOS. &#160; I didn&#8217;t debug or instrument too much into NSFileManager and why it performs so badly in this case. I suspect that this might be because NSFM supports setting a delegate, whose delegate methods get called multiple times during file operations. Possibly this isn&#8217;t optimized such that the check which methods are implemented (all are optional) is done when setting the delegate. If NSFM does tons of respondsToSelector: then that would explain the lag. The goal in this was was to get rid of a folder (and its contents) as fast as possible and to have any longer operations go on in the background. So my first instinct was to create a category on NSFileManager. Go Undercover Removing the above mentioned 160 MB folder would take 50 seconds (on iPad 1), but it would only require 8 ms to rename it. So the strategy became: 1) move it away into a temp location 2) actually delete it. // move it to a tmp name to that it appears gone CFUUIDRef newUniqueId = CFUUIDCreate&#40;kCFAllocatorDefault&#41;; CFStringRef newUniqueIdString = CFUUIDCreateString&#40;kCFAllocatorDefault, newUniqueId&#41;; NSString *tmpPath = &#91;NSTemporaryDirectory&#40;&#41; stringByAppendingPathComponent:&#40;__bridge NSString *&#41;newUniqueIdString&#93;; CFRelease&#40;newUniqueId&#41;; CFRelease&#40;newUniqueIdString&#41;; &#160; // make a file manager just for this thread/queue NSFileManager *fileManager = &#91;&#91;NSFileManager alloc&#93; init&#93;; &#160; if &#40;!&#91;fileManager moveItemAtPath:path toPath:tmpPath error:NULL&#93;&#41; &#123; // looks like the file is no longer there return; &#125; &#160; &#91;fileManager removeItemAtPath:tmpPath error:NULL&#93;; Now you see that I am creating a new fileManager. In the initial category I would simply use self here. But it was pointed out to me that it is unsafe to use the same NSFM instance from multiple threads. Also we don&#8217;t know &#8220;where it has been&#8221; &#8211; i.e. somebody might have set the delegate &#8211; so we make our own. A Touch of GCD The trusty performSelectorOnBackgroundThread: is so 2010, so we&#8217;ll make full use of the facilities provided by Grand Central Dispatch (GCD). Trust me, it&#8217;s easier than it sounds. Don&#8217;t let yourself be intimidated by the C and Blocks. We covered blocks before, today we shall dispatch them asynchronously. We will employ 3 GCD techniques in tandem: dispatch_async GCD groups dispatch_once In true GCD terminology everything happens on so-called Queues. As far as I can tell you can use Queue and Thread interchangeably. There are ways to get the main queue or background queues with certain priorities. But the one attribute of queues that we shall make use of is that they process one block of code at a time. This means you can feed multiple operations (packed in blocks) onto a background queue and be certain that they will be worked off sequentially. Sounds like an NSOperationQueue, doesn&#8217;t it? Well, NSOQ was reimplemented on GCD as soon that entered the language because it is way more efficient than regular threading. Now you can create anonymous queues, or you can group queues under a queue name. The latter is advantageous if you want to be able to wait for the queue to finish its work. The DTAsyncFileDeleter class that we are creating here is supposed to work off the items we give it to remove in sequence so that we can be certain that we don&#8217;t have two instances try to remove the same file at once. I initially thought about a simple @synchronize but that would have blocked if you wanted to remove two items in rapid succession. As a matter of fact I found that just mentioning the possibility of @synchronize in informed circles will get you many frowns and invariably several people will step forward to lecture you on how much more efficient GCD is. Let&#8217;s summarize the strategy: All instances of DTAsyncFileDeleter should use the same background queue. This queue should only be created once globally for all instances. And we need to somehow know if all operations are done. Oh, [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/02/fast-folder-nuking-on-ios/"></g:plusone></div><p>I got a strange bug report last week for iCatalog. Deleting of outdated catalogs takes too long, if we couldn&#8217;t show a HUD with a spinner while the deletion occurs. That was definitely one of these HUUUUU?! moments. I always thought that file deletion is instant on Unix since only an entry in a file table needs to be removed.</p>
<p>I grabbed an iPad 1 and deleted a 160 MB catalog. Only to find that the whole deletion &#8211; a simple NSFileManager removeItemAtPath &#8211; took 50 seconds. Uhm, no that is far from ideal to be blocking the main thread and interface for that long.</p>
<p>I played around a bit and over the course of the day, with some great help from several GCD experts on twitter, I pieced together a solution that might interest you if you ever have to delete large amounts of files in an instant. Before Cocoa, on Carbon, OSX offered a method called FSPathMoveObjectToTrashAsync, this is sort of the equivalent for iOS.</p>
<p><span id="more-5943"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>I didn&#8217;t debug or instrument too much into NSFileManager and why it performs so badly in this case. I suspect that this might be because NSFM supports setting a delegate, whose delegate methods get called multiple times during file operations. Possibly this isn&#8217;t optimized such that the check which methods are implemented (all are optional) is done when setting the delegate. If NSFM does tons of respondsToSelector: then that would explain the lag.</p>
<p>The goal in this was was to get rid of a folder (and its contents) as fast as possible and to have any longer operations go on in the background. So my first instinct was to create a category on NSFileManager.</p>
<h3>Go Undercover</h3>
<p>Removing the above mentioned 160 MB folder would take 50 seconds (on iPad 1), but it would only require 8 ms to rename it. So the strategy became: 1) move it away into a temp location 2) actually delete it.</p>

<div class="wp_codebox"><table><tr id="p5943162"><td class="code" id="p5943code162"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// move it to a tmp name to that it appears gone</span>
CFUUIDRef newUniqueId <span style="color: #002200;">=</span> CFUUIDCreate<span style="color: #002200;">&#40;</span>kCFAllocatorDefault<span style="color: #002200;">&#41;</span>;
CFStringRef newUniqueIdString <span style="color: #002200;">=</span> CFUUIDCreateString<span style="color: #002200;">&#40;</span>kCFAllocatorDefault, newUniqueId<span style="color: #002200;">&#41;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>tmpPath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>NSTemporaryDirectory<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> stringByAppendingPathComponent<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>__bridge <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>newUniqueIdString<span style="color: #002200;">&#93;</span>;
CFRelease<span style="color: #002200;">&#40;</span>newUniqueId<span style="color: #002200;">&#41;</span>;
CFRelease<span style="color: #002200;">&#40;</span>newUniqueIdString<span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// make a file manager just for this thread/queue</span>
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/"><span style="color: #400080;">NSFileManager</span></a> <span style="color: #002200;">*</span>fileManager <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/"><span style="color: #400080;">NSFileManager</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</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>fileManager moveItemAtPath<span style="color: #002200;">:</span>path toPath<span style="color: #002200;">:</span>tmpPath error<span style="color: #002200;">:</span><span style="color: #a61390;">NULL</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// looks like the file is no longer there</span>
	<span style="color: #a61390;">return</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">&#91;</span>fileManager removeItemAtPath<span style="color: #002200;">:</span>tmpPath error<span style="color: #002200;">:</span><span style="color: #a61390;">NULL</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>Now you see that I am creating a new fileManager. In the initial category I would simply use self here. But it was pointed out to me that it is unsafe to use the same NSFM instance from multiple threads. Also we don&#8217;t know &#8220;where it has been&#8221; &#8211; i.e. somebody might have set the delegate &#8211; so we make our own.</p>
<h3>A Touch of GCD</h3>
<p>The trusty performSelectorOnBackgroundThread: is so 2010, so we&#8217;ll make full use of the facilities provided by Grand Central Dispatch (GCD). Trust me, it&#8217;s easier than it sounds. Don&#8217;t let yourself be intimidated by the C and Blocks. We <a title="Functions as Parameters – Old &amp; New" href="http://www.cocoanetics.com/2011/05/functions-as-parameters-old-new/">covered blocks before</a>, today we shall dispatch them asynchronously.</p>
<p>We will employ 3 GCD techniques in tandem:</p>
<ol>
<li>dispatch_async</li>
<li>GCD groups</li>
<li>dispatch_once</li>
</ol>
<p>In true GCD terminology everything happens on so-called Queues. As far as I can tell you can use Queue and Thread interchangeably. There are ways to get the main queue or background queues with certain priorities. But the one attribute of queues that we shall make use of is that they process one block of code at a time.</p>
<p>This means you can feed multiple operations (packed in blocks) onto a background queue and be certain that they will be worked off sequentially. Sounds like an NSOperationQueue, doesn&#8217;t it? Well, NSOQ was reimplemented on GCD as soon that entered the language because it is way more efficient than regular threading.</p>
<p>Now you can create anonymous queues, or you can group queues under a queue name. The latter is advantageous if you want to be able to wait for the queue to finish its work.</p>
<p>The DTAsyncFileDeleter class that we are creating here is supposed to work off the items we give it to remove in sequence so that we can be certain that we don&#8217;t have two instances try to remove the same file at once. I initially thought about a simple @synchronize but that would have blocked if you wanted to remove two items in rapid succession. As a matter of fact I found that just mentioning the possibility of @synchronize in informed circles will get you many frowns and invariably several people will step forward to lecture you on how much more efficient GCD is.</p>
<p>Let&#8217;s summarize the strategy: All instances of DTAsyncFileDeleter should use the same background queue. This queue should only be created once globally for all instances. And we need to somehow know if all operations are done. Oh, and as a bonus it would be nice if the deletion would continue even after the app is suspended &#8230;</p>
<p>&#8220;use the same background queue&#8221; and &#8220;create once globally&#8221; are the terms that should trigger two ideas: static global variable and dispatch_once.</p>
<p>dispatch_once is a way in GCD to have something occur exactly once. Before GCD we would possibly have a static variable, check that against nil and only instantiate it if it is. The problem with this approach is that there would potentially be racing conditions where two threads would call the sharedInstance method at the same time and both would create the shared instance, but one would leak.</p>
<p>With GCD you define a static token and you are guaranteed that the dispatch_once block using this token is only going to be executed once. Really.</p>
<p>So in code, we have the static global variables at the top of our class, before the @implementation:</p>

<div class="wp_codebox"><table><tr id="p5943163"><td class="code" id="p5943code163"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">static</span> dispatch_queue_t _delQueue;
<span style="color: #a61390;">static</span> dispatch_group_t _delGroup;
<span style="color: #a61390;">static</span> dispatch_once_t onceToken;</pre></td></tr></table></div>

<p>And in the init we dispatch_once the creation of a queue and a group.</p>

<div class="wp_codebox"><table><tr id="p5943164"><td class="code" id="p5943code164"><pre class="objc" style="font-family:monospace;">dispatch_once<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>onceToken, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
	_delQueue <span style="color: #002200;">=</span> dispatch_queue_create<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">&quot;DTAsyncFileDeleterQueue&quot;</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
	_delGroup <span style="color: #002200;">=</span> dispatch_group_create<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>In this instance we don&#8217;t care about releasing these resources because these items should stay available until the app is terminated. GCD objects are very lightweight anyway, so not to worry.</p>
<p>And with the GCD trimmings set up we can wrap the above rename and delete code in a GCD block:</p>

<div class="wp_codebox"><table><tr id="p5943165"><td class="code" id="p5943code165"><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>removeItemAtPath<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>path
<span style="color: #002200;">&#123;</span>
	dispatch_group_async<span style="color: #002200;">&#40;</span>_delGroup, _delQueue, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
		<span style="color: #11740a; font-style: italic;">// rename and delete</span>
	<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Of course if you don&#8217;t need to wait on the queue then you can dispense with the group thing, a regular dispatch_async without group will work just the same. But we want to have a way for the outside world to wait, so we implement a method for that.</p>

<div class="wp_codebox"><table><tr id="p5943166"><td class="code" id="p5943code166"><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>waitUntilFinished
<span style="color: #002200;">&#123;</span>
	dispatch_group_wait<span style="color: #002200;">&#40;</span>_delGroup, DISPATCH_TIME_FOREVER<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>If the queue in our _delGroup is done, this function returns immediately. Otherwise it will wait forever. It&#8217;s almost too easy.</p>
<p>At this point our class is fully functional, but for convenience we also want to have a shared instance. So using what we now know about a token for dispatch_once we can construct our +sharedInstance method thusly:</p>

<div class="wp_codebox"><table><tr id="p5943167"><td class="code" id="p5943code167"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">static</span> DTAsyncFileDeleter <span style="color: #002200;">*</span>_sharedInstance;
&nbsp;
<span style="color: #a61390;">@implementation</span> DTAsyncFileDeleter
&nbsp;
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span>DTAsyncFileDeleter <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>sharedInstance
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">static</span> dispatch_once_t instanceOnceToken;
	dispatch_once<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>instanceOnceToken, <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
		_sharedInstance <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>DTAsyncFileDeleter alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">return</span> _sharedInstance;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Oh how convenient that is, anywhere we import the header we can do</p>

<div class="wp_codebox"><table><tr id="p5943168"><td class="code" id="p5943code168"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>DTAsyncFileDeleter sharedInstance<span style="color: #002200;">&#93;</span> removeItemAtPath<span style="color: #002200;">:</span>path<span style="color: #002200;">&#93;</span><span style="color: #002200;">:</span></pre></td></tr></table></div>

<p>It&#8217;s fast, it&#8217;s convenient, it&#8217;s safe. It&#8217;s totally Apple.</p>
<h3>Bonus: Automatic Background Task Completion</h3>
<p>If we left here then the deletion process would get suspended together with the app and possibly aborted if the app is killed. Of course it would resume normally the next time the app is brought to the foreground but such a deletion might take in the vicinity of one minute on a older iOS device, so that&#8217;s an ideal use case for iOS multitasking, aka background task completion.</p>
<p>A UIApplication is not suspended but left alive if it has one or more registered background tasks running. For this purpose you need to get a background task id from the shared UIApplication instance of your app. You need to set a completion handler that gets called if the task completion runs into the 10 min timeout. And you need to invalidate the background task in both cases, when timed out and when complete.</p>
<p>We just need to register a method for getting informed for the UIApplicationDidEnterBackgroundNotification and do that all. Of course we also check if multi tasking is available, just to be sure. (It is probably superfluous because it wouldn&#8217;t get the notification if it weren&#8217;t, right?)</p>

<div class="wp_codebox"><table><tr id="p5943169"><td class="code" id="p5943code169"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#pragma mark Notifications</span>
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>applicationDidEnterBackground<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNotification_Class/"><span style="color: #400080;">NSNotification</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>notification
<span style="color: #002200;">&#123;</span>
	UIDevice <span style="color: #002200;">*</span>device <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIDevice currentDevice<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>device respondsToSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>isMultitaskingSupported<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>device.multitaskingSupported<span style="color: #002200;">&#41;</span>
		<span style="color: #002200;">&#123;</span>
			<span style="color: #a61390;">return</span>;
		<span style="color: #002200;">&#125;</span>
	<span style="color: #002200;">&#125;</span>
&nbsp;
	UIApplication <span style="color: #002200;">*</span>app <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIApplication sharedApplication<span style="color: #002200;">&#93;</span>;
	__block UIBackgroundTaskIdentifier backgroundTaskID;
&nbsp;
	<span style="color: #a61390;">void</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span>completionBlock<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">=</span> <span style="color: #002200;">^</span><span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>app endBackgroundTask<span style="color: #002200;">:</span>backgroundTaskID<span style="color: #002200;">&#93;</span>;
		backgroundTaskID <span style="color: #002200;">=</span> UIBackgroundTaskInvalid;
	<span style="color: #002200;">&#125;</span>;
&nbsp;
	backgroundTaskID <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>app beginBackgroundTaskWithExpirationHandler<span style="color: #002200;">:</span>completionBlock<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// wait for all deletions to be done</span>
	<span style="color: #002200;">&#91;</span>self waitUntilFinished<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// ... when the syncing task completes:</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>backgroundTaskID <span style="color: #002200;">!=</span> UIBackgroundTaskInvalid<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		completionBlock<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;		
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Notice the __block which tags the backgroundTaskID variable such that it can be modified from inside the blocks. Without this attribute the value of the variable would be captured at the time of creation of the block. You can also see that I reuse the completionBlock variable because the same code is to be executed on the timeout as is on successful completion. The actual work is just to wait for the _delQueue to finish.</p>
<p>Update: Gavin McKenzie correctly pointed out to me that the above mentioned approach causes subsequent renames to have to wait for the entire async block to finish. This is why the public version of DTAsyncFileDeleter now has a second rename queue and performs the renames on a sync queue too. Gavin explains it thus:</p>
<blockquote><p>In the original implementation, additional callers would wait until all queued renames were finished &#8212; which is exactly what your code comment said. Which, could (in theory) mean that if 20 renames were queued, even the first rename operation would have to wait for the 20th queued rename to finish. That potential worried me, of having basically a block-wait on all the renames.</p>
<p>With the dispatch_sync approach each rename only has to wait for the previous rename to finish.</p></blockquote>
<p>Update 2: Steve Weller was the only one spotting the major problem with my approach and I needed some lab tasting to understand why he was right. The wait was occurring on the main thread of the application. So if that was blocking then the watchdog timer would see your app as not responding after 10 minutes and kill it. So the finally perfect approach was to do away with the notification and instead wrap each block with a task completion id, which &#8211; according to the documentation &#8211; can be called from background threads safely. Please look at the DTAsyncFileDeleter class in DTFoundation for the latest version.</p>
<h3>Conclusion</h3>
<p>GCD offers us a possibility to stick multiple items into a background queue that we don&#8217;t want to happen concurrently. The background queue will then happily work off these items and if we have it in a group then we can also wait for the completion in a safe way.</p>
<p>dispatch_once is a safe and convenient method of making sure that something only occurs a single time and thus ideal to create caches or shared instances.</p>
<p>Finally &#8211; according to an Apple engineer who was asked this question at a TechTalk &#8211; you can have as many background task completions as you wish, provided you clean up properly. Because if you don&#8217;t then your app will be killed. </p>
<p>One question that I couldn&#8217;t find an answer for at the time of this writing is if you can do away with the notification but instead &#8220;warp the operations in a background task&#8221; from the get go. My feeling is that this would be less elegant because you would have to dispatch onto the main thread to get a background task ID and to invalidate it in the end. But I am interested if you know any more elegant solutions&#8230;</p>
<p>The source code for DTAsyncFileDeleter can be found in my <a href="https://github.com/cocoanetics/DTFoundation">DTFoundation project on GitHub</a>.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5943&amp;md5=76f0aed545a36ec4a8c81a5ebb04b4fb" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/02/fast-folder-nuking-on-ios/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F02%2Ffast-folder-nuking-on-ios%2F&amp;language=en_GB&amp;category=text&amp;title=Fast+Folder+Nuking+on+iOS&amp;description=I+got+a+strange+bug+report+last+week+for+iCatalog.+Deleting+of+outdated+catalogs+takes+too+long%2C+if+we+couldn%26%238217%3Bt+show+a+HUD+with+a+spinner+while+the+deletion+occurs....&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Xcode Build Rules</title>
		<link>http://www.cocoanetics.com/2012/02/xcode-build-rules/</link>
		<comments>http://www.cocoanetics.com/2012/02/xcode-build-rules/#comments</comments>
		<pubDate>Fri, 03 Feb 2012 18:25:31 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5887</guid>
		<description><![CDATA[When I moved the default CSS rules into a separate file I was facing the old dilemma: how can I embed this in the static library but still be able to easily add contents to it via Xcode. I previously explained how you can turn any file into a c-Byte-array. But this still required manual work. I did a bit of researching and found that on regular Linux systems people seem to have a tool named objcopy which can copy files as their are into an object file (.o) which can be linked together to the final binary by the linker. But unfortunately this tool does not come with Xcode. So it is out of the question because I want everybody to be able to build DTCoreText. Xcode Build Rules come to the rescue. They can automate any kind of preprocessing you like and it turns out they are an easy solution for this very problem. &#160; There are essentially three kinds of source file that Xcode knows how to deal with (greatly simplified): c, c++ or Objective-C source code, or any code that can be somehow compiled header files other files &#8220;Other files&#8221;, if you add them to a target, are treated as resources that simply get copied into your app bundle. And now I&#8217;ll teach you how you can make any kind of file compilable. Be it some textures that you are compressing for building your game, or be it some resource that you want to embed into your binary. Make a Build Rule When Xcode is asked to compile a file it has a set of rules how it does that. So what we are going to do is to add our own rule how a css file is turned into a .c file. And for .c files are something that Xcode has a built-in rule for. So it can happen that you have two or more daisy chained rules that hand off their results to each other. It is somewhat inconvenient that you cannot define rules globally. Instead you have to repeat your custom rules for each target. To add your own rule, go into the projects info where you see your targets and on the target you want the rule for add it like shown. This rule matches all files that end with .css (asterisk is a wildcard) and executes a custom script: cd &#34;$INPUT_FILE_DIR&#34; # move into file dir, otherwise xxd takes the full path for the symbol /usr/bin/xxd -i &#34;$INPUT_FILE_NAME&#34; &#34;$DERIVED_SOURCES_DIR/$INPUT_FILE_BASE.css.c&#34; # builds a c file with a hex array I&#8217;m moving into the folder of the input file first because xxd will always take the full passed file path and turn it into the name of the c-array. This way it will just be named default_c and the length will be in default_c_len. The above rule is all it takes to teach Xcode how to turn a .css file into a .c file. Now the next step is to make sure that we are actually compiling the default.css file as opposed to copying it together with the other resources. Compile not Copy You can see that default.css is compiled by having it in the Compile Sources section of the Build Phases. If you build the project you see two hints about what happens now. Towards the top of the build log you see the preprocessing of the file. A little further down you see how the intermediate c file is being compiled. Further down the library tool puts all object files into the library archive. If you don&#8217;t believe me, you can employ the nm tool to inspect the symbols in the final product. nm DemoApp &#124; grep default_c 00045474 D _default_css 00045fe0 D _default_css_len These are the two symbols from the default.css.c file that made it into the final product. This guide wouldn&#8217;t be complete if I didn&#8217;t show you how to get to these symbols. Accessing the Objectified File I told you above that xxd uses the passed file name to make two variables, one for the c-style array, one for the length. Only change is that it has to turn the file name characters into a legal symbol, so dots are turned into underscores. In DTCSSStylesheet.m I am accessing this array like so. I define these two variables as external which prompts the linker to insert their correct address. + &#40;DTCSSStylesheet *&#41;defaultStyleSheet // external symbols generated via custom build rule and xxd extern unsigned char default_css&#91;&#93;; extern unsigned int default_css_len; &#125; And to get the string out of them is just as easy: + &#40;DTCSSStylesheet *&#41;defaultStyleSheet &#123; // get the data from the external symbol NSData *data = &#91;NSData dataWithBytes:default_css length:default_css_len&#93;; NSString *cssString = &#91;&#91;NSString alloc&#93; initWithData:data encoding:NSUTF8StringEncoding&#93;; &#160; return &#91;&#91;DTCSSStylesheet alloc&#93; initWithStyleBlock:cssString&#93;; &#125; This works because I know [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/02/xcode-build-rules/"></g:plusone></div><p>When I moved the default CSS rules into a separate file I was facing the old dilemma: how can I embed this in the static library but still be able to easily add contents to it via Xcode. I previously explained how you can <a title="Embedding Binary Resources" href="http://www.cocoanetics.com/2010/10/embedding-binary-resources/">turn any file into a c-Byte-array</a>. But this still required manual work.</p>
<p>I did a bit of researching and found that on regular Linux systems people seem to have a tool named objcopy which can copy files as their are into an object file (.o) which can be linked together to the final binary by the linker. But unfortunately this tool does not come with Xcode. So it is out of the question because I want everybody to be able to build DTCoreText.</p>
<p>Xcode Build Rules come to the rescue. They can automate any kind of preprocessing you like and it turns out they are an easy solution for this very problem.</p>
<p><span id="more-5887"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>There are essentially three kinds of source file that Xcode knows how to deal with (greatly simplified):</p>
<ul>
<li>c, c++ or Objective-C source code, or any code that can be somehow compiled</li>
<li>header files</li>
<li>other files</li>
</ul>
<p>&#8220;Other files&#8221;, if you add them to a target, are treated as resources that simply get copied into your app bundle.</p>
<p>And now I&#8217;ll teach you how you can make any kind of file compilable. Be it some textures that you are compressing for building your game, or be it some resource that you want to embed into your binary.</p>
<h3>Make a Build Rule</h3>
<p>When Xcode is asked to compile a file it has a set of rules how it does that. So what we are going to do is to add our own rule how a css file is turned into a .c file. And for .c files are something that Xcode has a built-in rule for. So it can happen that you have two or more daisy chained rules that hand off their results to each other.</p>
<p>It is somewhat inconvenient that you cannot define rules globally. Instead you have to repeat your custom rules for each target.</p>
<p>To add your own rule, go into the projects info where you see your targets and on the target you want the rule for add it like shown.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-02-03-um-7.02.06-PM.png"><img class="alignnone  wp-image-5889" title="Add a rule" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-02-03-um-7.02.06-PM.png" alt="" width="633" height="254" /></a></p>
<p>This rule matches all files that end with .css (asterisk is a wildcard) and executes a custom script:</p>

<div class="wp_codebox"><table><tr id="p5887182"><td class="code" id="p5887code182"><pre class="objc" style="font-family:monospace;">cd <span style="color: #bf1d1a;">&quot;$INPUT_FILE_DIR&quot;</span>  <span style="color: #6e371a;"># move into file dir, otherwise xxd takes the full path for the symbol</span>
<span style="color: #002200;">/</span>usr<span style="color: #002200;">/</span>bin<span style="color: #002200;">/</span>xxd <span style="color: #002200;">-</span>i <span style="color: #bf1d1a;">&quot;$INPUT_FILE_NAME&quot;</span> <span style="color: #bf1d1a;">&quot;$DERIVED_SOURCES_DIR/$INPUT_FILE_BASE.css.c&quot;</span> <span style="color: #6e371a;"># builds a c file with a hex array</span></pre></td></tr></table></div>

<p>I&#8217;m moving into the folder of the input file first because xxd will always take the full passed file path and turn it into the name of the c-array. This way it will just be named default_c and the length will be in default_c_len.</p>
<p>The above rule is all it takes to teach Xcode how to turn a .css file into a .c file. Now the next step is to make sure that we are actually compiling the default.css file as opposed to copying it together with the other resources.</p>
<h3>Compile not Copy</h3>
<p>You can see that default.css is compiled by having it in the Compile Sources section of the Build Phases.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-02-03-um-7.06.22-PM.png"><img class="alignnone  wp-image-5890" title="Compile css file" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-02-03-um-7.06.22-PM.png" alt="" width="629" height="207" /></a></p>
<p>If you build the project you see two hints about what happens now. Towards the top of the build log you see the preprocessing of the file. A little further down you see how the intermediate c file is being compiled.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-02-03-um-7.07.55-PM.png"><img class="alignnone  wp-image-5891" title="Preprocessing and Compiling" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-02-03-um-7.07.55-PM.png" alt="" width="631" height="214" /></a></p>
<p>Further down the library tool puts all object files into the library archive. If you don&#8217;t believe me, you can employ the nm tool to inspect the symbols in the final product.</p>

<div class="wp_codebox"><table><tr id="p5887183"><td class="code" id="p5887code183"><pre class="sh" style="font-family:monospace;">nm DemoApp | grep default_c
00045474 D _default_css
00045fe0 D _default_css_len</pre></td></tr></table></div>

<p>These are the two symbols from the default.css.c file that made it into the final product.</p>
<p>This guide wouldn&#8217;t be complete if I didn&#8217;t show you how to get to these symbols.</p>
<h3>Accessing the Objectified File</h3>
<p>I told you above that xxd uses the passed file name to make two variables, one for the c-style array, one for the length. Only change is that it has to turn the file name characters into a legal symbol, so dots are turned into underscores.</p>
<p>In DTCSSStylesheet.m I am accessing this array like so. I define these two variables as external which prompts the linker to insert their correct address.</p>

<div class="wp_codebox"><table><tr id="p5887184"><td class="code" id="p5887code184"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span>DTCSSStylesheet <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>defaultStyleSheet
<span style="color: #11740a; font-style: italic;">// external symbols generated via custom build rule and xxd</span>
<span style="color: #a61390;">extern</span> <span style="color: #a61390;">unsigned</span> <span style="color: #a61390;">char</span> default_css<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #a61390;">extern</span> <span style="color: #a61390;">unsigned</span> <span style="color: #a61390;">int</span> default_css_len;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>And to get the string out of them is just as easy:</p>

<div class="wp_codebox"><table><tr id="p5887185"><td class="code" id="p5887code185"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span>DTCSSStylesheet <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>defaultStyleSheet
<span style="color: #002200;">&#123;</span>
   <span style="color: #11740a; font-style: italic;">// get the data from the external symbol</span>
   <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/"><span style="color: #400080;">NSData</span></a> <span style="color: #002200;">*</span>data <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/"><span style="color: #400080;">NSData</span></a> dataWithBytes<span style="color: #002200;">:</span>default_css length<span style="color: #002200;">:</span>default_css_len<span style="color: #002200;">&#93;</span>;
   <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>cssString <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> alloc<span style="color: #002200;">&#93;</span> initWithData<span style="color: #002200;">:</span>data encoding<span style="color: #002200;">:</span>NSUTF8StringEncoding<span style="color: #002200;">&#93;</span>;
&nbsp;
   <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>DTCSSStylesheet alloc<span style="color: #002200;">&#93;</span> initWithStyleBlock<span style="color: #002200;">:</span>cssString<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This works because I know that all my source files are UTF8 encoded, i.e. one byte per (normal) character. It is quite handy to have the default_css_len integer telling us the length of the array, because in c an array is just a pointer to the first byte.</p>
<h3>Conclusion</h3>
<p>If you know how to employ custom build rules to your advantage many tasks that you would have previously run external scripts for now become part of the build process. What you can do with this knowledge is only limited by your imagination &#8230; and your scripting skills.</p>
<p>But the general advantage of build rules versus external programs is that they are part of the project. So if they use standard commands they are portable to other developer&#8217;s machines. Perfect for Open Source projects.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5887&amp;md5=4af7587e6b75dcc81ddd9ca30897f36d" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/02/xcode-build-rules/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F02%2Fxcode-build-rules%2F&amp;language=en_GB&amp;category=text&amp;title=Xcode+Build+Rules&amp;description=When+I+moved+the+default+CSS+rules+into+a+separate+file+I+was+facing+the+old+dilemma%3A+how+can+I+embed+this+in+the+static+library+but+still+be+able...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>GitHub Fork, Fix, Pull Request</title>
		<link>http://www.cocoanetics.com/2012/01/github-fork-fix-pull-request/</link>
		<comments>http://www.cocoanetics.com/2012/01/github-fork-fix-pull-request/#comments</comments>
		<pubDate>Thu, 26 Jan 2012 13:10:03 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5859</guid>
		<description><![CDATA[In this post I will to demonstrate how you can contribute to an Open Source project hosted on GitHub. I previously blogged about how you can make and apply patches, which is certainly one way. But on GitHub there is an even cooler method, one that is also less work on the project maintainer. &#160; For the sake of this tutorial I shall pretend that there is an issue with a project by Matt Galloway, then I&#8217;ll fork his project. After fixing the issue I will push my changes online to my fork and finally notify Matt about these changes via a so-called &#8220;Pull Request&#8221;. A prerequisite for this tutorial is to have your GitHub account and local git set up previously. Step 1 &#8211; We have an Issue Your first thought should be to document that in GitHub&#8217;s excellent bug tracking system. Each Open Source project there has a list of Issues (which are the bugs and feature requests). I found two things to improve in the project and so I added two issues. We could hope for the project&#8217;s owner to fix that for us, but &#8211; being smart developers &#8211; we can also proceed to fix the issues ourselves. From the get go we won&#8217;t have writing access to the GitHub repository (unless the owner gives it to us, which is rare). You can see that this is the case if you only see the HTTP and Git Read-Only options on the repo URL: The usual method is to make a copy of this project in our own area on GitHub where we CAN write to. This copy is what they call a &#8220;Fork&#8221;. Step 2 &#8211; Stick a Fork in it To make a fork you klick the &#8220;Fork&#8221; button at the top right of the project main page. After some &#8220;hardcore forking action&#8221; you end up on your own copy of the project. And there is now an extra option &#8220;SSH&#8221; telling you that you have read and write access to that. A fork is a complete copy of the original project including all previous history. The reason for this that with Git every copy of a repository is always a full clone, so that each clone can also serve as a backup. This illustrates the distributed nature of Git, as opposed to centralized Source Code Management (SCM) systems like Subversion which has a central server. Step 3 &#8211; Clone Wars To work on our copy of the project we need to clone it to our hard disk. You can use the excellent official GitHub app but personally I prefer to work in terminal. I open terminal, go to a place where I want the copy of the project to be and issue the command: git clone git@github.com:Cocoanetics/ios-library-with-resources.git The URL used is the SSH one I copied from the web page. This results in a ios-library-with-resources folder appearing in the current working directory. Step 4 &#8211; Fix-Tours Now we can do our changes. So I open the Xcode project. The first thing I am fixing for this example is to add the two sub-project products as dependency so that they get automatically built if somebody builds the containing app. You see an M (for Modified) appear next to the root of the project tree which means that the project file has been modified. Each such fix should become one commit. So we right-click on MyLibraryTest, Source Control, Commit Selected Files. This opens a dialog that shows which files were modified and prompts for a commit message. Since we fixed issue number #001 with that we also add this tag, because later we will see that GitHub conveniently links this commit with the issue via this number. This committing basically saves the current state in your local Git repository (your clone) and adds your message to that. Actually it did a bit more than that, because Git has a an extra step called &#8220;staging&#8221; before committing. In staging you select the modifications you want to be part of the commit by Adding them to the staging area. The second part then does this saving. If you do this via the Xcode interface you don&#8217;t need this staging phase because you specifically selected the files to commit already via the project navigator. The second issue to fix is to change a build setting on the sub-project. This time the M appears next to the MyLibrary.xcodeproj which really means the project.pbxproj file contained in the MyLibrary.xcodeproj bundle. (Remember that a bundle is a folder that looks like a file) This time let&#8217;s do the committing on the command like, like a real pro. First let&#8217;s see the status. git status # On branch master # Your branch is ahead of 'origin/master' by 1 commit. # # Changes not staged for [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/01/github-fork-fix-pull-request/"></g:plusone></div><p>In this post I will to demonstrate how you can contribute to an Open Source project hosted on GitHub. I previously blogged about <a title="How to Make and Apply Patches" href="http://www.cocoanetics.com/2011/12/how-to-make-and-apply-patches/">how you can make and apply patches</a>, which is certainly one way. But on GitHub there is an even cooler method, one that is also less work on the project maintainer.</p>
<p><span id="more-5859"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>For the sake of this tutorial I shall pretend that there is an issue with a project by Matt Galloway, then I&#8217;ll fork his project. After fixing the issue I will push my changes online to my fork and finally notify Matt about these changes via a so-called &#8220;Pull Request&#8221;.</p>
<p>A prerequisite for this tutorial is to have your GitHub account and local git <a href="http://www.cocoanetics.com/2011/01/starting-an-opensource-project-on-github/">set up previously</a>.</p>
<h3>Step 1 &#8211; We have an Issue</h3>
<p>Your first thought should be to document that in GitHub&#8217;s excellent bug tracking system. Each Open Source project there has a list of Issues (which are the bugs and feature requests). I found two things to improve in the project and so I added two issues.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-12.53.44-PM.png"><img class="alignnone  wp-image-5860" title="Issue" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-12.53.44-PM.png" alt="" width="650" height="524" /></a></p>
<p>We could hope for the project&#8217;s owner to fix that for us, but &#8211; being smart developers &#8211; we can also proceed to fix the issues ourselves. From the get go we won&#8217;t have writing access to the GitHub repository (unless the owner gives it to us, which is rare). You can see that this is the case if you only see the HTTP and Git Read-Only options on the repo URL:</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.00.19-PM.png"><img class="alignnone  wp-image-5861" title="Read-Only" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.00.19-PM.png" alt="" width="637" height="79" /></a></p>
<p>The usual method is to make a copy of this project in our own area on GitHub where we CAN write to. This copy is what they call a &#8220;Fork&#8221;.</p>
<h3>Step 2 &#8211; Stick a Fork in it</h3>
<p>To make a fork you klick the &#8220;Fork&#8221; button at the top right of the project main page. After some &#8220;hardcore forking action&#8221; you end up on your own copy of the project. And there is now an extra option &#8220;SSH&#8221; telling you that you have read and write access to that.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.03.02-PM.png"><img class="alignnone  wp-image-5862" title="Forked" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.03.02-PM.png" alt="" width="758" height="165" /></a></p>
<p>A fork is a complete copy of the original project including all previous history. The reason for this that with Git every copy of a repository is always a full clone, so that each clone can also serve as a backup. This illustrates the distributed nature of Git, as opposed to centralized Source Code Management (SCM) systems like Subversion which has a central server.</p>
<h3>Step 3 &#8211; Clone Wars</h3>
<p>To work on our copy of the project we need to clone it to our hard disk. You can use the excellent <a href="http://mac.github.com/">official GitHub app</a> but personally I prefer to work in terminal. I open terminal, go to a place where I want the copy of the project to be and issue the command:</p>

<div class="wp_codebox"><table><tr id="p5859193"><td class="code" id="p5859code193"><pre class="objc" style="font-family:monospace;">git clone git@github.com<span style="color: #002200;">:</span>Cocoanetics<span style="color: #002200;">/</span>ios<span style="color: #002200;">-</span>library<span style="color: #002200;">-</span>with<span style="color: #002200;">-</span>resources.git</pre></td></tr></table></div>

<p>The URL used is the SSH one I copied from the web page. This results in a ios-library-with-resources folder appearing in the current working directory.</p>
<h3>Step 4 &#8211; Fix-Tours</h3>
<p>Now we can do our changes. So I open the Xcode project.</p>
<p>The first thing I am fixing for this example is to add the two sub-project products as dependency so that they get automatically built if somebody builds the containing app.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.17.57-PM.png"><img class="alignnone  wp-image-5863" title="Issue 1" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.17.57-PM.png" alt="" width="608" height="335" /></a></p>
<p>You see an M (for Modified) appear next to the root of the project tree which means that the project file has been modified. Each such fix should become one commit. So we right-click on MyLibraryTest, Source Control, Commit Selected Files. This opens a dialog that shows which files were modified and prompts for a commit message.</p>
<p>Since we fixed issue number #001 with that we also add this tag, because later we will see that GitHub conveniently links this commit with the issue via this number.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.24.03-PM.png"><img class="alignnone  wp-image-5864" title="First commit" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.24.03-PM.png" alt="" width="608" height="326" /></a></p>
<p>This committing basically saves the current state in your local Git repository (your clone) and adds your message to that. Actually it did a bit more than that, because Git has a an extra step called &#8220;staging&#8221; before committing.</p>
<p>In staging you select the modifications you want to be part of the commit by Adding them to the staging area. The second part then does this saving. If you do this via the Xcode interface you don&#8217;t need this staging phase because you specifically selected the files to commit already via the project navigator.</p>
<p>The second issue to fix is to change a build setting on the sub-project.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.33.27-PM.png"><img class="alignnone  wp-image-5865" title="Issue 2" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.33.27-PM.png" alt="" width="557" height="271" /></a></p>
<p>This time the M appears next to the MyLibrary.xcodeproj which really means the project.pbxproj file contained in the MyLibrary.xcodeproj bundle. (Remember that a bundle is a folder that looks like a file)</p>
<p>This time let&#8217;s do the committing on the command like, like a real pro. First let&#8217;s see the status.</p>

<div class="wp_codebox"><table><tr id="p5859194"><td class="code" id="p5859code194"><pre class="sh" style="font-family:monospace;">git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
# Changes not staged for commit:
#   (use &quot;git add ...&quot; to update what will be committed)
#   (use &quot;git checkout -- ...&quot; to discard changes in working directory)
#
#	modified:   MyLibrary/MyLibrary.xcodeproj/project.pbxproj
#
no changes added to commit (use &quot;git add&quot; and/or &quot;git commit -a&quot;)</pre></td></tr></table></div>

<p>This shows that we are ahead of our fork (origin/master) by 1 commit, which is the previous one we did. And it shows that the project file for the sub-project was modified. We issue a &#8220;git commit -a&#8221; which stages all modified files for the commit and immediately prompts us for a commit message in the currently set up text editor.</p>
<p>There is a second shortcut that GitHub recognizes besides the #002 tag. If you write &#8220;closes&#8221; or &#8220;fixes&#8221; in front of the hashtag it not only references the issue, but also marks it as closed. How convenient!</p>
<p>&#8220;Set Skip Install YES for resource bundle to prevent copying that into Archive. closes #002&#8243;</p>
<p>I type my message into the VIM that opened and save/exit via ESC, :wq, ENTER.</p>
<p>Now we have two local commits (git log to see them), next we need to push them to our online repository. We just had modifications to the project file in these two examples, but &#8211; trust me &#8211; it works just as well for code changes.</p>
<h3>Step 5 &#8211; Push Up</h3>
<p>When we cloned the project to our local hard disk Git was nice enough to automatically configure the location where it came from as so called &#8220;Remote&#8221;, the default name is &#8220;origin&#8221;. You can have multiple remote places set up and choose which to push.</p>
<p>The command for us is:</p>

<div class="wp_codebox"><table><tr id="p5859195"><td class="code" id="p5859code195"><pre class="sh" style="font-family:monospace;">git push origin master</pre></td></tr></table></div>

<p>&#8220;origin&#8221; is the remote I told you about, &#8220;master&#8221; means that you are pushing this to the master branch, which is the default branch.</p>
<p>To check if our changes have really arrived online I like to check the commits view on GitHub. And indeed they have.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.50.45-PM.png"><img class="alignnone  wp-image-5866" title="Commits have landed" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.50.45-PM.png" alt="" width="756" height="249" /></a></p>
<p>We could end here and many people do. They just make a copy of an Open Source project for the case that the original repository disappears. But since we are playing nice we want to offer our improvements to the original project&#8217;s owner.</p>
<h3>Step 6 &#8211; I just called to say &#8220;Please Pull Me!&#8221;</h3>
<p>Just like for the fork we find a &#8220;Pull Request&#8221; button at the top right of the GitHub website of our fork. Push it and you get a nice overview of what is contained in the request.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.56.06-PM.png"><img class="alignnone  wp-image-5867" title="Pull Request" src="http://www.cocoanetics.com/files/Bildschirmfoto-2012-01-26-um-1.56.06-PM.png" alt="" width="660" height="500" /></a></p>
<p>There are some advanced options regarding milestones and assignments, but we&#8217;ll ignore these for now. You&#8217;ll notice that the pull request automatically generates a new number, #3 in our case. So you can not only reference issues with your commit messages, but the same thing is possible for pull requests.</p>
<p>The final step is not for us, but for the original project&#8217;s owner to perform.</p>
<h3>Step 7 &#8211; Accepted!</h3>
<p>As owner of a GitHub repo it is up to you whether you want to accept the changes into your repository. If you kept your commits small and &#8211; for code changes &#8211; added some good comments to aid understanding then the owner will be happy to accept them. It saves him from doing the work that you did and all he needs is to push the green merge button.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2012-01-26-at-13.41.53.png"><img class="alignnone  wp-image-5871" title="Accepting" src="http://www.cocoanetics.com/files/Screen-Shot-2012-01-26-at-13.41.53.png" alt="" width="669" height="422" /></a></p>
<p>The button to accept the changes is only green if the merge of the code can be performed automatically. If the author did some changes on his own that conflict with yours then the button is gray stating that the changes cannot be merged automatically. In this unfortunate situation either one of you needs to pull the other&#8217;s changes and manually resolve the merging conflicts. But this is a topic for another day.</p>
<h3>Conclusion</h3>
<p>I suggest you find yourself a a GitHub project to contribute to and try out this process to shed the timid feeling. It really is quite idiot proof.</p>
<p>People put their projects on GitHub not only so that you get free source code to use in your apps. They also hope that other developers might find and fix bugs. And every once in a while you see a pull request that makes you think &#8220;OMG I&#8217;m not worthy!&#8221; because those are the gems that really teach you something.</p>
<p>And this is why they call it collaborative coding.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5859&amp;md5=450103b7bf2d416c4504c16e867994e4" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/01/github-fork-fix-pull-request/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F01%2Fgithub-fork-fix-pull-request%2F&amp;language=en_GB&amp;category=text&amp;title=GitHub+Fork%2C+Fix%2C+Pull+Request&amp;description=In+this+post+I+will+to+demonstrate+how+you+can+contribute+to+an+Open+Source+project+hosted+on+GitHub.+I+previously+blogged+about+how+you+can+make+and+apply+patches%2C...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Taming HTML Parsing with libxml (2)</title>
		<link>http://www.cocoanetics.com/2012/01/taming-html-parsing-with-libxml-2/</link>
		<comments>http://www.cocoanetics.com/2012/01/taming-html-parsing-with-libxml-2/#comments</comments>
		<pubDate>Fri, 20 Jan 2012 08:54:06 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5834</guid>
		<description><![CDATA[The parsing of HTML necessary for my DTCoreText open source project is done entirely with the sophisticated use of NSScanner. But it has been long on my list to rewrite all of this parsing with a the industry standard libxml2 which comes preinstalled on all iOS devices. Not only is this potentially much faster in dealing with large chunks of HTML. It probably is also more intelligent in correcting structural errors of the HTML code you throw at it. In part 1 of this series I showed you how to add the libxml2 library to your project and explained the basic concepts of using libxml2 for parsing any odd HTML snippet into a DOM. In this here part 2 we will create an Objective-C based wrapper around libml2 so that we can use it just like NSXMLParser, only for HTML. &#160; There are basically two methods &#8211; approaches &#8211; to handling XML/HTML: DOM or SAX. DOM (short for Document Object Model) refers to building a tree of nodes and leaves which you then can query for information based on their path (with XPath). SAX (short for Simple API for XML) basically walks through the the document and sends you events as it discovers things. For example the begin of an element, the end of it, when a comment was found, etc. NSXMLParser is a SAX parser for well-formed XML. That means you can use it only on XML, it cannot deal with the nature of HTML where some elements might not require that you close them. But if you look at the delegate protocol and compare it to the SAX interface of libxml2 you find an eerie resemblance. It might as well be that NSXMLParser is just a wrapper around the XML SAX interface of libxml2. As we have previously learned we know that libxml2 also possesses a HTML parser which reuses most of the same internal data structures as its XML cousin. So we shall endeavor to create DTHTMLParser as a SAX parser for HTML. Don&#8217;t worry about piecing together all the source code from this article, I will put that online in my DTFoundation project. Instead I want you to follow my lead and understand the pieces. The libxml2 SAX Interface The SAX interface works such that you register a handler function &#8211; in C &#8211; for each SAX event that you are interested in. This is done via a C-structure of type htmlSAXHandler which is nothing more than an aggregate of multiple C-function pointers. In the libxml headers you often see some &#8220;html&#8230;&#8221; data structure typedef&#8217;d into one with &#8220;xml&#8221; as prefix. The reason for this is that it reuses whatever it can from the XML parser. But this also adds confusion &#8211; as I found through my experimenting &#8211; because some of the events that make sense for parsing XML don&#8217;t fire for HTML, like for example the one that reports CDATA elements. HTML does not have those, but the function pointer is still present in the htmlSAXHandler struct. By CMD+Clicking on a type we can swim upstream to find the original definition of htmlSAXHandler: htmlSAXHandler = xmlSAXHandler = _xmlSAXHandler = struct _xmlSAXHandler &#123; internalSubsetSAXFunc internalSubset; isStandaloneSAXFunc isStandalone; hasInternalSubsetSAXFunc hasInternalSubset; hasExternalSubsetSAXFunc hasExternalSubset; resolveEntitySAXFunc resolveEntity; getEntitySAXFunc getEntity; entityDeclSAXFunc entityDecl; notationDeclSAXFunc notationDecl; attributeDeclSAXFunc attributeDecl; elementDeclSAXFunc elementDecl; unparsedEntityDeclSAXFunc unparsedEntityDecl; setDocumentLocatorSAXFunc setDocumentLocator; startDocumentSAXFunc startDocument; endDocumentSAXFunc endDocument; startElementSAXFunc startElement; endElementSAXFunc endElement; referenceSAXFunc reference; charactersSAXFunc characters; ignorableWhitespaceSAXFunc ignorableWhitespace; processingInstructionSAXFunc processingInstruction; commentSAXFunc comment; warningSAXFunc warning; errorSAXFunc error; fatalErrorSAXFunc fatalError; /* unused error() get all the errors */ getParameterEntitySAXFunc getParameterEntity; cdataBlockSAXFunc cdataBlock; externalSubsetSAXFunc externalSubset; unsigned int initialized; /* The following fields are extensions available only on version 2 */ void *_private; startElementNsSAX2Func startElementNs; endElementNsSAX2Func endElementNs; xmlStructuredErrorFunc serror; &#125;; All these function pointer types are aptly named SomethingFunc and we&#8217;ll get to how these need to look like in a minute. The problem for us to solve how to bridge from our Objective-C paradigm (using self, properties, IVARs) into the C-function paradigm (no access to our parser object). This problem is compounded by the fact that we are building this with ARC so that we don&#8217;t have to deal with memory management any more. Our resulting class will run on iOS 4 and above. Somehow we need to pass enough information to each event-function so that we can communicate with the parser object. There are two reasonable possibilities: either we pass a reference to the parser instance or we pass a pointer to a struct that contains multiple values that we might need. I decided for the first because it seems cleaner to me. libxml2 provides a concept of a user_data pointer that is passed to the event-functions together with other relevant information. We can use (abuse?) this for passing a reference to self. ARC requires this to be be cast to (__bridge void *) which in [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/01/taming-html-parsing-with-libxml-2/"></g:plusone></div><p>The parsing of HTML necessary for my <a title="NSAttributedString+HTML Q&amp;A" href="http://www.cocoanetics.com/2011/08/nsattributedstringhtml-qa/">DTCoreText</a> open source project is done entirely with the sophisticated use of NSScanner. But it has been long on my list to rewrite all of this parsing with a the industry standard libxml2 which comes preinstalled on all iOS devices. Not only is this potentially much faster in dealing with large chunks of HTML. It probably is also more intelligent in correcting structural errors of the HTML code you throw at it.</p>
<p>In <a title="Taming HTML Parsing with libxml (1)" href="http://www.cocoanetics.com/2011/09/taming-html-parsing-with-libxml-1/">part 1 of this series</a> I showed you how to add the libxml2 library to your project and explained the basic concepts of using libxml2 for parsing any odd HTML snippet into a DOM. In this here part 2 we will create an Objective-C based wrapper around libml2 so that we can use it just like NSXMLParser, only for HTML.</p>
<p><span id="more-5834"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>There are basically two methods &#8211; approaches &#8211; to handling XML/HTML: DOM or SAX. DOM (short for Document Object Model) refers to building a tree of nodes and leaves which you then can query for information based on their path (with XPath). SAX (short for Simple API for XML) basically walks through the the document and sends you events as it discovers things. For example the begin of an element, the end of it, when a comment was found, etc.</p>
<p>NSXMLParser is a SAX parser for well-formed XML. That means you can use it only on XML, it cannot deal with the nature of HTML where some elements might not require that you close them. But if you look at the delegate protocol and compare it to the SAX interface of libxml2 you find an eerie resemblance. It might as well be that NSXMLParser is just a wrapper around the XML SAX interface of libxml2.</p>
<p>As we have previously learned we know that libxml2 also possesses a HTML parser which reuses most of the same internal data structures as its XML cousin. So we shall endeavor to create DTHTMLParser as a SAX parser for HTML.</p>
<p>Don&#8217;t worry about piecing together all the source code from this article, I will put that online in my <a href="https://github.com/Cocoanetics/DTFoundation">DTFoundation</a> project. Instead I want you to follow my lead and understand the pieces.</p>
<h3>The libxml2 SAX Interface</h3>
<p>The SAX interface works such that you register a handler function &#8211; in C &#8211; for each SAX event that you are interested in. This is done via a C-structure of type htmlSAXHandler which is nothing more than an aggregate of multiple <a title="Functions as Parameters – Old &amp; New" href="http://www.cocoanetics.com/2011/05/functions-as-parameters-old-new/">C-function pointers</a>.</p>
<p>In the libxml headers you often see some &#8220;html&#8230;&#8221; data structure typedef&#8217;d into one with &#8220;xml&#8221; as prefix. The reason for this is that it reuses whatever it can from the XML parser. But this also adds confusion &#8211; as I found through my experimenting &#8211; because some of the events that make sense for parsing XML don&#8217;t fire for HTML, like for example the one that reports CDATA elements. HTML does not have those, but the function pointer is still present in the htmlSAXHandler struct.</p>
<p>By CMD+Clicking on a type we can swim upstream to find the original definition of htmlSAXHandler:</p>
<p>htmlSAXHandler = xmlSAXHandler = _xmlSAXHandler =</p>

<div class="wp_codebox"><table><tr id="p5834208"><td class="code" id="p5834code208"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">struct</span> _xmlSAXHandler <span style="color: #002200;">&#123;</span>
    internalSubsetSAXFunc internalSubset;
    isStandaloneSAXFunc isStandalone;
    hasInternalSubsetSAXFunc hasInternalSubset;
    hasExternalSubsetSAXFunc hasExternalSubset;
    resolveEntitySAXFunc resolveEntity;
    getEntitySAXFunc getEntity;
    entityDeclSAXFunc entityDecl;
    notationDeclSAXFunc notationDecl;
    attributeDeclSAXFunc attributeDecl;
    elementDeclSAXFunc elementDecl;
    unparsedEntityDeclSAXFunc unparsedEntityDecl;
    setDocumentLocatorSAXFunc setDocumentLocator;
    startDocumentSAXFunc startDocument;
    endDocumentSAXFunc endDocument;
    startElementSAXFunc startElement;
    endElementSAXFunc endElement;
    referenceSAXFunc reference;
    charactersSAXFunc characters;
    ignorableWhitespaceSAXFunc ignorableWhitespace;
    processingInstructionSAXFunc processingInstruction;
    commentSAXFunc comment;
    warningSAXFunc warning;
    errorSAXFunc error;
    fatalErrorSAXFunc fatalError; <span style="color: #11740a; font-style: italic;">/* unused error() get all the errors */</span>
    getParameterEntitySAXFunc getParameterEntity;
    cdataBlockSAXFunc cdataBlock;
    externalSubsetSAXFunc externalSubset;
    <span style="color: #a61390;">unsigned</span> <span style="color: #a61390;">int</span> initialized;
    <span style="color: #11740a; font-style: italic;">/* The following fields are extensions available only on version 2 */</span>
    <span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>_private;
    startElementNsSAX2Func startElementNs;
    endElementNsSAX2Func endElementNs;
    xmlStructuredErrorFunc serror;
<span style="color: #002200;">&#125;</span>;</pre></td></tr></table></div>

<p>All these function pointer types are aptly named SomethingFunc and we&#8217;ll get to how these need to look like in a minute. The problem for us to solve how to bridge from our Objective-C paradigm (using self, properties, IVARs) into the C-function paradigm (no access to our parser object).</p>
<p>This problem is compounded by the fact that we are building this with ARC so that we don&#8217;t have to deal with memory management any more. Our resulting class will run on iOS 4 and above. Somehow we need to pass enough information to each event-function so that we can communicate with the parser object.</p>
<p>There are two reasonable possibilities: either we pass a reference to the parser instance or we pass a pointer to a struct that contains multiple values that we might need. I decided for the first because it seems cleaner to me.</p>
<p>libxml2 provides a concept of a user_data pointer that is passed to the event-functions together with other relevant information. We can use (abuse?) this for passing a reference to self. ARC requires this to be be cast to (__bridge void *) which in plain English means: <em>&#8220;please treat this as just some typeless memory pointer and also don&#8217;t worry about retaining or releasing. I&#8217;ll take care of that, don&#8217;t panic.&#8221;</em></p>
<p>Like any self-respecting class we&#8217;ll start out with a good block of IVAR definitions and and init method.</p>

<div class="wp_codebox"><table><tr id="p5834209"><td class="code" id="p5834code209"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@implementation</span> DTHTMLParser
<span style="color: #002200;">&#123;</span>
    htmlSAXHandler _handler;
&nbsp;
    NSStringEncoding _encoding;
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/"><span style="color: #400080;">NSData</span></a> <span style="color: #002200;">*</span>_data;
&nbsp;
    __unsafe_unretained <span style="color: #a61390;">id</span> &lt;DTHTMLParserDelegate&gt; _delegate;
    htmlParserCtxtPtr _parserContext;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Notice that I&#8217;m defining the IVARs in the implementation, not the interface (in the header). This is possible as of using the new Apple LLVM compiler and provides for a nice way to hide the IVARs that we don&#8217;t want to be visible.</p>

<div class="wp_codebox"><table><tr id="p5834210"><td class="code" id="p5834code210"><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>initWithData<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/"><span style="color: #400080;">NSData</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>data encoding<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSStringEncoding<span style="color: #002200;">&#41;</span>encoding
<span style="color: #002200;">&#123;</span>
	self <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>super init<span style="color: #002200;">&#93;</span>;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>self<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		_data <span style="color: #002200;">=</span> data;
		_encoding <span style="color: #002200;">=</span> encoding;
&nbsp;
		xmlSAX2InitHtmlDefaultSAXHandler<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>_handler<span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #a61390;">return</span> self;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>We save the data and the encoding into our IVARs, _data being a strong reference to it. That means that it retains it during the lifetime of our parser and will only release it when the parser goes away.</p>
<p>We also initialize the _handler structure via the xmlSAX2InitHtmlDefaultSAXHandler function. This sets up some initial internals and also chooses the SAX2 method for our work. There&#8217;s also an older SAX1 method, but we obviously prefer the newer one. This setup has to happen inside the init method because right after such an instance of a DTHTMLParser is create we want to be able to set the delegate which should take care of wiring up the needed functions.</p>
<p>Each event-function should have a corresponding delegate method in our DTHTMLParserDelegate protocol, but to avoid unnecessary function-calling we only add the functions to the handler for which the delegate actually implements the function.</p>

<div class="wp_codebox"><table><tr id="p5834211"><td class="code" id="p5834code211"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#pragma mark Properties</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>setDelegate<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>__unsafe_unretained id&lt;DTHTMLParserDelegate&gt;<span style="color: #002200;">&#41;</span>delegate;
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>delegate <span style="color: #002200;">!=</span> _delegate<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		_delegate <span style="color: #002200;">=</span> delegate;
&nbsp;
		<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>_delegate respondsToSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>parserDidStartDocument<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
		<span style="color: #002200;">&#123;</span>
			_handler.startDocument <span style="color: #002200;">=</span> _startDocument;
		<span style="color: #002200;">&#125;</span>
		<span style="color: #a61390;">else</span>
		<span style="color: #002200;">&#123;</span>
			_handler.startDocument <span style="color: #002200;">=</span> <span style="color: #a61390;">NULL</span>;
		<span style="color: #002200;">&#125;</span>
&nbsp;
		<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>_delegate respondsToSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>parserDidEndDocument<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
		<span style="color: #002200;">&#123;</span>
			_handler.endDocument <span style="color: #002200;">=</span> _endDocument;
		<span style="color: #002200;">&#125;</span>
		<span style="color: #a61390;">else</span>
		<span style="color: #002200;">&#123;</span>
			_handler.endDocument <span style="color: #002200;">=</span> <span style="color: #a61390;">NULL</span>;
		<span style="color: #002200;">&#125;</span>
<span style="color: #11740a; font-style: italic;">// ...</span></pre></td></tr></table></div>

<p>This way when you set the delegate it is inspected one by one whether it responds to certain methods of the protocol. And whenever it does the corresponding function pointer is set in the _handler IVAR.</p>
<p>At the top of the file we need to define these functions. If we do just that then the compiler will warn us for all of these implementations that there was &#8220;no previous prototype&#8221;. In C a you call the first line of a C-function it&#8217;s prototype. So we just have an extra block for these.</p>

<div class="wp_codebox"><table><tr id="p5834212"><td class="code" id="p5834code212"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#pragma mark Event function prototypes</span>
&nbsp;
<span style="color: #a61390;">void</span> _startDocument<span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>context<span style="color: #002200;">&#41;</span>;
<span style="color: #a61390;">void</span> _endDocument<span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>context<span style="color: #002200;">&#41;</span>;
<span style="color: #a61390;">void</span> _startElement<span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>context, <span style="color: #a61390;">const</span> xmlChar <span style="color: #002200;">*</span>name,<span style="color: #a61390;">const</span> xmlChar <span style="color: #002200;">**</span>atts<span style="color: #002200;">&#41;</span>;
<span style="color: #a61390;">void</span> _endElement<span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>context, <span style="color: #a61390;">const</span> xmlChar <span style="color: #002200;">*</span>name<span style="color: #002200;">&#41;</span>;
<span style="color: #a61390;">void</span> _characters<span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>context, <span style="color: #a61390;">const</span> xmlChar <span style="color: #002200;">*</span>ch, <span style="color: #a61390;">int</span> len<span style="color: #002200;">&#41;</span>;
<span style="color: #a61390;">void</span> _comment<span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>context, <span style="color: #a61390;">const</span> xmlChar <span style="color: #002200;">*</span>value<span style="color: #002200;">&#41;</span>;
<span style="color: #a61390;">void</span> _error<span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>context, <span style="color: #a61390;">const</span> <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>msg, ...<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>Wherever you see a context parameter this will be the user_data pointer we will provide. And for example the _startElement function gets a name and an array of attributes as well. The xmlChar type is just a char. This is actually always provided as UTF8-encoded string regardless of what the data is encoded as.</p>
<p>Let&#8217;s look first at an easy event-function and then at a more complex one.</p>

<div class="wp_codebox"><table><tr id="p5834213"><td class="code" id="p5834code213"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">void</span> _startDocument<span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>context<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
    DTHTMLParser <span style="color: #002200;">*</span>myself <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>__bridge DTHTMLParser <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>context;
&nbsp;
    <span style="color: #002200;">&#91;</span>myself.delegate parserDidStartDocument<span style="color: #002200;">:</span>myself<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>You see how I cast the void pointer back into a pointer of type DTHTMLParser. I have to name the variable different than &#8220;self&#8221; because that is a reserved word. Then I can simply call the delegate method that corresponds to this event function. </p>
<p>By the way, these are the delegate methods we want to implement:</p>

<div class="wp_codebox"><table><tr id="p5834214"><td class="code" id="p5834code214"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@class</span> DTHTMLParser;
&nbsp;
<span style="color: #a61390;">@protocol</span> DTHTMLParserDelegate &lt;NSObject&gt;
&nbsp;
@optional
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>parserDidStartDocument<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>DTHTMLParser <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>parser;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>parserDidEndDocument<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>DTHTMLParser <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>parser;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>parser<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>DTHTMLParser <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>parser didStartElement<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>elementName attributes<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/"><span style="color: #400080;">NSDictionary</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>attributeDict;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>parser<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>DTHTMLParser <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>parser didEndElement<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>elementName;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>parser<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>DTHTMLParser <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>parser foundCharacters<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span><span style="color: #a61390;">string</span>;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>parser<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>DTHTMLParser <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>parser foundComment<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>comment;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>parser<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>DTHTMLParser <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>parser parseErrorOccurred<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/"><span style="color: #400080;">NSError</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>parseError;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>The @class is necessary before the protocol definition because a good delegate protocol also passes a reference to the caller. This also enables the casual reader of your code to know at a glance that this method belongs to a protocol connected to this class.</p>
<p>Now for something more complex, let&#8217;s look at didStartElement. The complexity of this method results from the arts parameter being alternating key, value, key, value etc.</p>

<div class="wp_codebox"><table><tr id="p5834215"><td class="code" id="p5834code215"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">void</span> _startElement<span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>context, <span style="color: #a61390;">const</span> xmlChar <span style="color: #002200;">*</span>name,<span style="color: #a61390;">const</span> xmlChar <span style="color: #002200;">**</span>atts<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
	DTHTMLParser <span style="color: #002200;">*</span>myself <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>__bridge DTHTMLParser <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>context;
&nbsp;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>nameStr <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> stringWithUTF8String<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">char</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>name<span style="color: #002200;">&#93;</span>;
&nbsp;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/"><span style="color: #400080;">NSMutableDictionary</span></a> <span style="color: #002200;">*</span>attributes <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>atts<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>key <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
		<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>value <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
		attributes <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/"><span style="color: #400080;">NSMutableDictionary</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #a61390;">int</span> i<span style="color: #002200;">=</span><span style="color: #2400d9;">0</span>;
		<span style="color: #a61390;">while</span> <span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>
		<span style="color: #002200;">&#123;</span>
			<span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>att <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">char</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>atts<span style="color: #002200;">&#91;</span>i<span style="color: #002200;">++</span><span style="color: #002200;">&#93;</span>;
&nbsp;
			<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>key<span style="color: #002200;">&#41;</span>
			<span style="color: #002200;">&#123;</span>
				<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>att<span style="color: #002200;">&#41;</span>
				<span style="color: #002200;">&#123;</span>
					<span style="color: #11740a; font-style: italic;">// we're done</span>
					<span style="color: #a61390;">break</span>;
				<span style="color: #002200;">&#125;</span>
&nbsp;
				key <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> stringWithUTF8String<span style="color: #002200;">:</span>att<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: #a61390;">if</span> <span style="color: #002200;">&#40;</span>att<span style="color: #002200;">&#41;</span>
				<span style="color: #002200;">&#123;</span>
					value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> stringWithUTF8String<span style="color: #002200;">:</span>att<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: #11740a; font-style: italic;">// solo attribute</span>
					value <span style="color: #002200;">=</span> key;
				<span style="color: #002200;">&#125;</span>
&nbsp;
				<span style="color: #002200;">&#91;</span>attributes setObject<span style="color: #002200;">:</span>value forKey<span style="color: #002200;">:</span>key<span style="color: #002200;">&#93;</span>;
&nbsp;
				value <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
				key <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
			<span style="color: #002200;">&#125;</span>
		<span style="color: #002200;">&#125;</span>
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #002200;">&#91;</span>myself.delegate parser<span style="color: #002200;">:</span>myself didStartElement<span style="color: #002200;">:</span>nameStr attributes<span style="color: #002200;">:</span>attributes<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>The while loop walks through the attributes and and when a NULL is encountered where a key would be then it breaks out of the loop. It is also necessary to deal with a situation where there is only an attribute name, but no value because HTML also allows that. Theoretically one attribute could also be occurring multiple times, but we ignore this. For later convenience we want the key/values for the attributes in an NSDictionary.</p>
<p>The final piece is how the parsing actually is started. For this we have a parse method, just like NSXMLParser.</p>

<div class="wp_codebox"><table><tr id="p5834216"><td class="code" id="p5834code216"><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>parse
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>dataBytes <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">char</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span>_data bytes<span style="color: #002200;">&#93;</span>;
	<span style="color: #a61390;">int</span> dataSize <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>_data length<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// detect encoding if necessary</span>
	xmlCharEncoding charEnc <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>_encoding<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		charEnc <span style="color: #002200;">=</span> xmlDetectCharEncoding<span style="color: #002200;">&#40;</span>dataBytes, dataSize<span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#125;</span>
	<span style="color: #a61390;">else</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #11740a; font-style: italic;">// convert the encoding</span>
		<span style="color: #11740a; font-style: italic;">// TODO: proper mapping from _encoding to xmlCharEncoding</span>
		CFStringEncoding cfenc <span style="color: #002200;">=</span> CFStringConvertNSStringEncodingToEncoding<span style="color: #002200;">&#40;</span>_encoding<span style="color: #002200;">&#41;</span>;
		CFStringRef cfencstr <span style="color: #002200;">=</span> CFStringConvertEncodingToIANACharSetName<span style="color: #002200;">&#40;</span>cfenc<span style="color: #002200;">&#41;</span>;
		<span style="color: #a61390;">const</span> <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>enc <span style="color: #002200;">=</span> CFStringGetCStringPtr<span style="color: #002200;">&#40;</span>cfencstr, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
&nbsp;
		charEnc <span style="color: #002200;">=</span> xmlParseCharEncoding<span style="color: #002200;">&#40;</span>enc<span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// create a parse context</span>
	_parserContext <span style="color: #002200;">=</span> htmlCreatePushParserCtxt<span style="color: #002200;">&#40;</span><span style="color: #002200;">&amp;</span>_handler, <span style="color: #002200;">&#40;</span>__bridge <span style="color: #a61390;">void</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>self, 
		dataBytes, dataSize, <span style="color: #a61390;">NULL</span>, charEnc<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// set some options</span>
	htmlCtxtUseOptions<span style="color: #002200;">&#40;</span>_parserContext, HTML_PARSE_RECOVER | HTML_PARSE_NONET |
		HTML_PARSE_COMPACT<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// parse!</span>
	<span style="color: #a61390;">int</span> result <span style="color: #002200;">=</span> htmlParseDocument<span style="color: #002200;">&#40;</span>_parserContext<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">return</span> <span style="color: #002200;">&#40;</span>result<span style="color: #002200;">==</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>There is a xmlDetectCharEncoding function in libxml to try and detect the encoding of the data which we invoke if the passed encoding is 0. The way to convert the NSStringEncoding into the xmlCharEncoding is only work shift, that needs some improving, possibly by simply having a big switch statement. Maybe later.</p>
<p>There are multiple ways how you can parse a document, some of which take individual parameters, some take a html parsing context. I settled on using the one for the push interface because there the htmlParseDocument function does not return a pointer to an html document tree (DOM), but instead a result that is 0 for success or -1 for error.</p>
<p>It is my understanding that this variant does not actually build the entire tree but keeps just enough state information to track the current hierarchy level inside the HTML tree. The push parser variant also has the ability to parse chunks of HTML data as they become available, e.g. while downloading. But exploring that is outside our scope for now.</p>
<h3>Conclusion</h3>
<p>Once your eyes have gotten used to the coding style of libxml2 you can start to appreciate the plethora of functions that it provides. You can also peruse the <a href="http://xmlsoft.org/html/index.html">official reference manual online</a>.</p>
<p>Finally I invite your collaboration on using and helping to polish DTHTMLParser if you have any need for parsing HTML text from within your iOS apps. Look for it on the GitHub DTFoundation project as soon as I can add a bit of AppleDoc-style documentation to it.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5834&amp;md5=71505f45c772506d51675dd3c0636f33" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/01/taming-html-parsing-with-libxml-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F01%2Ftaming-html-parsing-with-libxml-2%2F&amp;language=en_GB&amp;category=text&amp;title=Taming+HTML+Parsing+with+libxml+%282%29&amp;description=The+parsing+of+HTML+necessary+for+my+DTCoreText+open+source+project+is+done+entirely+with+the+sophisticated+use+of+NSScanner.+But+it+has+been+long+on+my+list+to+rewrite...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Helping Xcode Find Library Headers</title>
		<link>http://www.cocoanetics.com/2012/01/helping-xcode-find-library-headers/</link>
		<comments>http://www.cocoanetics.com/2012/01/helping-xcode-find-library-headers/#comments</comments>
		<pubDate>Thu, 19 Jan 2012 15:26:46 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5825</guid>
		<description><![CDATA[In my previous article about Sub-Projects in Xcode I showed you how you can have an Xcode project as a dependency. The advantage of this is that you can update your library from within the same project and debug into the sub-project&#8217;s code. One thing that was not immediately obvious was how you deal with the problem that Xcode cannot find your sub-project&#8217;s library headers. Hence this writeup. &#160; A header file generally informs the compiler what c-functions, global variables, Object-C methods and classes exist in an object file. All these are generally called &#8220;symbols&#8221;. Build Process Review The build process consists of these three steps: Preprocessor &#8211; this takes care of including/importing header files into your source code, essentially pasting the content of the specified file right into your source code for building. This step also replaces all instances of #defined values with what you defined them to be. Compiler &#8211; this goes through all the .m files and builds an object file with .o extension for each. Each item that is not coming from the same .m file is marked as an external symbol. Linker &#8211; this merges all the object files into one big binary while at the same time linking the symbols with the actual implementations. Header files do not actually contain executable code, but instead they tell the compiler which names and functions it should accept. It is the linker then that resolves these references. In short: If you want to use something which is implemented outside the current .m file than you need the appropriate import for that. There are two kinds of imports: &#60;path/header.h&#62; with angle brackets &#8211; these are meant for system or &#8220;global&#8221; includes. &#8220;path/header.h&#8221; with double quotes &#8211; these are meant for items that are limited in scope to your current project You have probably used both already, the one with the angle brackets for including headers that Apple provided. The one with the double quotes for accessing your own classes. Paths are usually relative paths because everybody has a different folder structure on his hard disk. Get the Headers into Your App The easiest way to get the headers into your project is to just add them. But you should generally refrain from duplicating your code for convenience, because then you have to perform an update on every copy of the file. A variation of this theme would be to not add the file itself, but just a reference. But this approach would also make your project dependent on your folder structure. Don&#8217;t do it, just don&#8217;t. If you have followed the Sub-Projects guide you are already perfectly set up to get to the header while still keeping the project self-contained and independent from the file system layout. You only need to tell the outer Xcode project &#8211; probably your app that includes sub-projects for some static libraries &#8211; where it can find the necessary headers from the sub-project. Again you have multiple options: you can point it to the source code folder where the .h files are located. Or you can point it to the build output folder. Both are equally viable but if you work with static universal frameworks &#8211; as I do &#8211; then you can only use option two without losing your mind. On my projects that contain reusable code I usually have multiple targets. One for a universal static framework &#8211; which is very convenient to add to a project because it automatically sets up the library and header paths for you when you drag it into your project. I have a second target for a static library because this allows for using the project as a sub-project and have the outer project link to the static library product. Because the framework conveniently bundles together multiple .h files you usually have the general name of the framework as path, i.e. you find &#60;MobFox/MobFox.h&#62; as the import of choice. For for example an Apple framework &#60;Foundation/Foundation.h&#62;. Contrasting the MobFox/ path the actual location of the header file is PROJECT_ROOT/Core, so no MobFox path component there. This is the reason why we cannot point the containing app to the source folder because there is no header file MobFox.h inside a folder named MobFox. So via approach number 1 we would never find the header, we want to take door number two which is to point Xcode to the static library build output folder. But for this to work some setup is necessary. Specifying Public Header Output Location After building the static library Xcode will also copy certain headers to the output folder. A header can be public, project or private. Public means that it will be distributed together with the library. Project and Private won&#8217;t. You can set this for every header file individually. Headers for objects that [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2012/01/helping-xcode-find-library-headers/"></g:plusone></div><p>In my previous article about <a title="Sub-Projects in Xcode" href="http://www.cocoanetics.com/2011/12/sub-projects-in-xcode/">Sub-Projects in Xcode</a> I showed you how you can have an Xcode project as a dependency. The advantage of this is that you can update your library from within the same project and debug into the sub-project&#8217;s code.</p>
<p>One thing that was not immediately obvious was how you deal with the problem that Xcode cannot find your sub-project&#8217;s library headers. Hence this writeup.</p>
<p><span id="more-5825"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>A header file generally informs the compiler what c-functions, global variables, Object-C methods and classes exist in an object file. All these are generally called &#8220;symbols&#8221;.</p>
<h3>Build Process Review</h3>
<p>The build process consists of these three steps:</p>
<ol>
<li><strong>Preprocessor</strong> &#8211; this takes care of including/importing header files into your source code, essentially pasting the content of the specified file right into your source code for building. This step also replaces all instances of #defined values with what you defined them to be.</li>
<li><strong>Compiler</strong> &#8211; this goes through all the .m files and builds an object file with .o extension for each. Each item that is not coming from the same .m file is marked as an external symbol.</li>
<li><strong>Linker</strong> &#8211; this merges all the object files into one big binary while at the same time linking the symbols with the actual implementations.</li>
</ol>
<p>Header files do not actually contain executable code, but instead they tell the compiler which names and functions it should accept. It is the linker then that resolves these references. In short: If you want to use something which is implemented outside the current .m file than you need the appropriate import for that.</p>
<p>There are two kinds of imports:</p>
<ul>
<li>&lt;path/header.h&gt; with angle brackets &#8211; these are meant for system or &#8220;global&#8221; includes.</li>
<li>&#8220;path/header.h&#8221; with double quotes &#8211; these are meant for items that are limited in scope to your current project</li>
</ul>
<p>You have probably used both already, the one with the angle brackets for including headers that Apple provided. The one with the double quotes for accessing your own classes. Paths are usually relative paths because everybody has a different folder structure on his hard disk.</p>
<h3>Get the Headers into Your App</h3>
<p>The easiest way to get the headers into your project is to just add them. But you should generally refrain from duplicating your code for convenience, because then you have to perform an update on every copy of the file. A variation of this theme would be to not add the file itself, but just a reference. But this approach would also make your project dependent on your folder structure. Don&#8217;t do it, just don&#8217;t.</p>
<p>If you have followed the Sub-Projects guide you are already perfectly set up to get to the header while still keeping the project self-contained and independent from the file system layout. You only need to tell the outer Xcode project &#8211; probably your app that includes sub-projects for some static libraries &#8211; where it can find the necessary headers from the sub-project. Again you have multiple options: you can point it to the source code folder where the .h files are located. Or you can point it to the build output folder. Both are equally viable but if you work with static universal frameworks &#8211; as I do &#8211; then you can only use option two without losing your mind.</p>
<p>On my projects that contain reusable code I usually have multiple targets. One for a universal static framework &#8211; which is very convenient to add to a project because it automatically sets up the library and header paths for you when you drag it into your project. I have a second target for a static library because this allows for using the project as a sub-project and have the outer project link to the static library product. Because the framework conveniently bundles together multiple .h files you usually have the general name of the framework as path, i.e. you find &lt;MobFox/MobFox.h&gt; as the import of choice. For for example an Apple framework &lt;Foundation/Foundation.h&gt;.</p>
<p>Contrasting the MobFox/ path the actual location of the header file is PROJECT_ROOT/Core, so no MobFox path component there. This is the reason why we cannot point the containing app to the source folder because there is no header file MobFox.h inside a folder named MobFox. So via approach number 1 we would never find the header, we want to take door number two which is to point Xcode to the static library build output folder. But for this to work some setup is necessary.</p>
<h3>Specifying Public Header Output Location</h3>
<p>After building the static library Xcode will also copy certain headers to the output folder. A header can be public, project or private. Public means that it will be distributed together with the library. Project and Private won&#8217;t. You can set this for every header file individually. Headers for objects that you want to be able to see from your app should be Public.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2012-01-19-at-3.48.06-PM.png"><img class="alignnone  wp-image-5826" title="Public, Project, Private" src="http://www.cocoanetics.com/files/Screen-Shot-2012-01-19-at-3.48.06-PM.png" alt="" width="640" height="92" /></a></p>
<p>If you now build the static library and look at the build log you will see that at the very end the public headers are copied somewhere:</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2012-01-19-at-3.52.39-PM.png"><img class="alignnone  wp-image-5827" title="Library output after build" src="http://www.cocoanetics.com/files/Screen-Shot-2012-01-19-at-3.52.39-PM.png" alt="" width="713" height="182" /></a></p>
<p>We are astonished to find a path ending in Build/Products/Debug-iphoneos/usr/local/include for the two public header files. The reason for this being the default setting is that traditionally people would build binary files for the system they are working on. But that&#8217;s not what we want. So we go into the build settings for the static library target and adjust this. Don&#8217;t put this entry into either the Debug or Release lines, but into the line above these so that it may override both.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2012-01-19-at-4.00.42-PM.png"><img class="alignnone  wp-image-5828" title="changing the public header output path" src="http://www.cocoanetics.com/files/Screen-Shot-2012-01-19-at-4.00.42-PM.png" alt="" width="608" height="467" /></a></p>
<p>When we now build we see the output go to Build/Products/Debug-iphoneos/MobFox &#8211; as we want it. It is this extra MobFox path component that enables us to use the &lt;MobFox/MobFox.h&gt; style of including later on.</p>
<p>Now back to our app that is including this sub-project&#8217;s static library. There we now need to tell the compiler where it can find the above folder. It so happens that when building Xcode usually uses the same output folder for all products it needs to build, namely whatever is in the $(CONFIGURATION_BUILD_DIR) variable at the time. This in turn is set by default to $(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME).</p>
<p>The final piece of the puzzle to know is where to put that. This depends on the include style that I explained above. Double quoted includes need the path in &#8220;User Header Search Paths&#8221;. Angle-bracketed includes need the regular &#8220;Header Search Paths&#8221;. We are forced to use the latter due to the framework. We don&#8217;t need to check the Recursive box because at the given location there is a MobFox folder.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2012-01-19-at-4.12.28-PM.png"><img class="alignnone size-full wp-image-5829" title="Screen Shot 2012-01-19 at 4.12.28 PM" src="http://www.cocoanetics.com/files/Screen-Shot-2012-01-19-at-4.12.28-PM.png" alt="" width="887" height="513" /></a></p>
<p>The &lt;Multiple values&gt; might cause you to pause for a second, but remember what I told you above. The configuration (Debug/Release) is part of this path and so even though you put the same variable in there, the actual result is a different one. Note that these values are bold because the target settings override the settings specified by the project. You can revert to the project settings by selecting the line and hitting CMD+Backspace.</p>
<p>There is an alternate option to put this path in the &#8220;User Header Search Paths&#8221; instead, but then you need to set &#8220;Always Search User Paths&#8221; to Yes. This will cause the compiler to also search the user header paths for angle bracket includes. Though personally I prefer the other option that needs less settings.</p>
<p>The other steps for building are explained in the Sub-Projects posts. If you carry them out (link with target), you will find that now your app finds the headers and successfully builds.</p>
<h3>Conclusion</h3>
<p>If Xcode complains that it cannot find a header then you should make sure that it is indeed in a place where it can find it. There is an abundance of default settings that may seem daunting, but if you know what to look for you can quickly find why your header cannot be found.</p>
<p>I wrote this article because I myself was stumped by not being able to explain why a project couldn&#8217;t find the MobFox header. So another learning of this episode is that you should not assume that the owner of your sub-project has set everything up correctly. In my case I too was missing the custom header output path setting. Errare humanum est.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5825&amp;md5=2d7dee18cea6ddcc2a930d578c490b8e" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2012/01/helping-xcode-find-library-headers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F01%2Fhelping-xcode-find-library-headers%2F&amp;language=en_GB&amp;category=text&amp;title=Helping+Xcode+Find+Library+Headers&amp;description=In+my+previous+article+about+Sub-Projects+in+Xcode%C2%A0I+showed+you+how+you+can+have+an+Xcode+project+as+a+dependency.+The+advantage+of+this+is+that+you+can+update+your...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>How to Make and Apply Patches</title>
		<link>http://www.cocoanetics.com/2011/12/how-to-make-and-apply-patches/</link>
		<comments>http://www.cocoanetics.com/2011/12/how-to-make-and-apply-patches/#comments</comments>
		<pubDate>Tue, 27 Dec 2011 09:33:23 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5756</guid>
		<description><![CDATA[Sometimes you want to tell somebody how you fixed a problem in their code, but for some reason the code is not on github so you cannot send them a pull request. If you felt really smart then you might put the changes you made into an e-mail, like &#8220;in file1.m:102 you change it to x, in file2.m:54 you make change y&#8221;. Thought this doesn&#8217;t really help the developer you are trying to help. Even when following your change instructions to the letter it is a tedious and error-prone method of applying your changes. Thanks to M. Douglas McIlroy, Adjunct Professor at Dartmouth Colleague &#8211; one of the early Unix pioneers &#8211; there is a better way. He invented the form of diff that we are using today to get the Difference between two versions of a file. And Larry Wall who invented the patch command which can take a diff file and effectively apply it to files. &#160; Honestly I was afraid of using patch before, never having played with it. What you don&#8217;t know you fear&#8230;. but since you are reading this article I now finally did, so that I can explain its usage. Making a Patch Let&#8217;s try with a simple text file first. file1.txt Here's some text. And a second line. And a third line. A fourth line. file1_changed.txt Here's some text. And a third line. A fourth line changed. To get the difference between these files we just diff them: diff file1.txt file1_changed.txt This produces this output: 2d1 &#60; And a second line. 4c3 &#60; A fourth line. --- &#62; A fourth line changed. We see that diff features each changed block with a sort of address. We removed line two, so we see that the d in 2d1 probably means deleted. And the c in 4c3 probably means changed. If a line was changed you first see the original line prefixed by a less-than, then three dashes and then the changed line prefixed by a greater-than. diff also has a -y flag that puts the changes side-by-side, which more clearly visualizes the changes. This kind of output is called the &#8220;normal&#8221; format. To be able to use the diff for patching this is missing some vital information, namely which file the changes belong to. For this purpose you have to use the &#8220;unified&#8221; format which you get with the -u flag. We also pipe the output into a new file. diff -u file1.txt file1_changed.txt &#38;gt; patch.diff This results in the patch file to have this content: --- file1.txt 2011-12-25 12:17:30.000000000 +0100 +++ file1_changed.txt 2011-12-25 12:01:30.000000000 +0100 @@ -1,4 +1,3 @@ Here's some text. -And a second line. And a third line. -A fourth line. +A fourth line changed. You can see that has information about which files are involved. Also you have minus and plus prefixes. A minus with a plus following means that the line was changed. Just a minus means that the line was only present in the original, i.e. deleted. Just a plus means that line was only present in the modified version, i.e. inserted. Let&#8217;s Patch Appling the patch we just created is very simple. If the current working directory contains both the patch and the to-be-patched file all we need is: patch &#38;lt; patch.diff You get an output telling you while files where touched. As soon as you have applied a patch, calling the patch command again with the same patch will get you a message about this giving you the option to ignore individual &#8220;hunks&#8221; which is what these blocks of changes are called. Multiple Files For multiple files the process is only slightly more complex. Say you have a a folder &#8220;original&#8221; and a folder &#8220;changed&#8221; and the latter contains multiple changed versions of the files in the former. If you call diff passing a folder name instead of a file name then this causes diff to compare file1 in one folder against file1 in the second folder, exactly what we need. There are a couple of additional flags for diff that are of use in this case: -r to recurse through all subfolders of the passed folders -u to get the &#8220;unified format&#8221; output -p prints the c-function a change was contained in -N treats absent files as empty So we go into the folder where our &#8220;original&#8221; and &#8220;changed&#8221; folders are located in and do: diff -rupN original changed &#38;gt; original.patch With this patch file it is easiest if you just move into the root of the original and copy the patch there. Then you can apply it without any additional parameters. Even though the diff contains the original and changed path prefixes it figures out that you must have meant the file contained in the current working directory. cd original cp ../original.patch . patch &#38;lt; [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/12/how-to-make-and-apply-patches/"></g:plusone></div><p>Sometimes you want to tell somebody how you fixed a problem in their code, but for some reason the code is not on github so you cannot send them a pull request. If you felt really smart then you might put the changes you made into an e-mail, like &#8220;in file1.m:102 you change it to x, in file2.m:54 you make change y&#8221;.</p>
<p>Thought this doesn&#8217;t really help the developer you are trying to help. Even when following your change instructions to the letter it is a tedious and error-prone method of applying your changes.</p>
<p>Thanks to <a href="http://www.cs.dartmouth.edu/~doug/">M. Douglas McIlroy</a>, Adjunct Professor at Dartmouth Colleague &#8211; one of the early Unix pioneers &#8211; there is a better way. He invented the form of <strong>diff</strong> that we are using today to get the Difference between two versions of a file. And <a href="http://www.wall.org/~larry/">Larry Wall</a> who invented the <strong>patch</strong> command which can take a diff file and effectively apply it to files.</p>
<p><span id="more-5756"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>Honestly I was afraid of using patch before, never having played with it. What you don&#8217;t know you fear&#8230;. but since you are reading this article I now finally did, so that I can explain its usage.</p>
<h3>Making a Patch</h3>
<p>Let&#8217;s try with a simple text file first.</p>
<p><strong>file1.txt</strong></p>
<pre>Here's some text.
And a second line.
And a third line.
A fourth line.</pre>
<p><strong>file1_changed.txt</strong></p>
<pre>Here's some text.
And a third line.
A fourth line changed.</pre>
<p>To get the difference between these files we just diff them:</p>

<div class="wp_codebox"><table><tr id="p5756238"><td class="code" id="p5756code238"><pre class="sh" style="font-family:monospace;">diff file1.txt file1_changed.txt</pre></td></tr></table></div>

<p>This produces this output:</p>
<pre>2d1
&lt; And a second line.
4c3
&lt; A fourth line. --- &gt; A fourth line changed.</pre>
<p>We see that diff features each changed block with a sort of address. We removed line two, so we see that the d in 2d1 probably means deleted. And the c in 4c3 probably means changed. If a line was changed you first see the original line prefixed by a less-than, then three dashes and then the changed line prefixed by a greater-than. diff also has a -y flag that puts the changes side-by-side, which more clearly visualizes the changes.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2011-12-25-um-12.07.08.png"><img class="alignnone  wp-image-5758" title="side-by-side diff" src="http://www.cocoanetics.com/files/Bildschirmfoto-2011-12-25-um-12.07.08.png" alt="" width="528" height="164" /></a></p>
<p>This kind of output is called the &#8220;normal&#8221; format. To be able to use the diff for patching this is missing some vital information, namely which file the changes belong to. For this purpose you have to use the &#8220;unified&#8221; format which you get with the -u flag. We also pipe the output into a new file.</p>

<div class="wp_codebox"><table><tr id="p5756239"><td class="code" id="p5756code239"><pre class="sh" style="font-family:monospace;">diff -u file1.txt file1_changed.txt &amp;gt; patch.diff</pre></td></tr></table></div>

<p>This results in the patch file to have this content:</p>
<pre>--- file1.txt	2011-12-25 12:17:30.000000000 +0100
+++ file1_changed.txt	2011-12-25 12:01:30.000000000 +0100
@@ -1,4 +1,3 @@
 Here's some text.
-And a second line.
 And a third line.
-A fourth line.
+A fourth line changed.</pre>
<p>You can see that has information about which files are involved. Also you have minus and plus prefixes. A minus with a plus following means that the line was changed. Just a minus means that the line was only present in the original, i.e. deleted. Just a plus means that line was only present in the modified version, i.e. inserted.</p>
<h3>Let&#8217;s Patch</h3>
<p>Appling the patch we just created is very simple. If the current working directory contains both the patch and the to-be-patched file all we need is:</p>

<div class="wp_codebox"><table><tr id="p5756240"><td class="code" id="p5756code240"><pre class="sh" style="font-family:monospace;">patch &amp;lt; patch.diff</pre></td></tr></table></div>

<p>You get an output telling you while files where touched. As soon as you have applied a patch, calling the patch command again with the same patch will get you a message about this giving you the option to ignore individual &#8220;hunks&#8221; which is what these blocks of changes are called.</p>
<h3>Multiple Files</h3>
<p>For multiple files the process is only slightly more complex. Say you have a a folder &#8220;original&#8221; and a folder &#8220;changed&#8221; and the latter contains multiple changed versions of the files in the former.</p>
<p>If you call diff passing a folder name instead of a file name then this causes diff to compare file1 in one folder against file1 in the second folder, exactly what we need. There are a couple of additional flags for diff that are of use in this case:</p>
<ul>
<li>-r to recurse through all subfolders of the passed folders</li>
<li>-u to get the &#8220;unified format&#8221; output</li>
<li>-p prints the c-function a change was contained in</li>
<li>-N treats absent files as empty</li>
</ul>
<p>So we go into the folder where our &#8220;original&#8221; and &#8220;changed&#8221; folders are located in and do:</p>

<div class="wp_codebox"><table><tr id="p5756241"><td class="code" id="p5756code241"><pre class="sh" style="font-family:monospace;">diff -rupN original changed &amp;gt; original.patch</pre></td></tr></table></div>

<p>With this patch file it is easiest if you just move into the root of the original and copy the patch there. Then you can apply it without any additional parameters. Even though the diff contains the original and changed path prefixes it figures out that you must have meant the file contained in the current working directory.</p>

<div class="wp_codebox"><table><tr id="p5756242"><td class="code" id="p5756code242"><pre class="sh" style="font-family:monospace;">cd original
cp ../original.patch .
patch &amp;lt; original.patch</pre></td></tr></table></div>

<p>There is one parameter of the patch command that you might need if the paths mentioned in the diff refer to a different folder structure than you have on your own machine. The man page of patch has this to say about -p:</p>
<blockquote><p>-pnum or &#8211;strip=num<br />
Strip the smallest prefix containing num leading slashes from each file name found in the patch file. A sequence of one or more adjacent slashes is counted as a single slash. This controls how file names found in the patch file are treated, in case you keep your files in a different directory than the person who sent out the patch. For example, supposing the file name in the patch file was</p>
<p>/u/howard/src/blurfl/blurfl.c</p>
<p>setting -p0 gives the entire file name unmodified, -p1 gives</p>
<p>u/howard/src/blurfl/blurfl.c</p>
<p>without the leading slash, -p4 gives</p>
<p>blurfl/blurfl.c</p>
<p>and not specifying -p at all just gives you blurfl.c. Whatever you end up with is looked for either in the current directory, or the directory specified by the -d option.</p></blockquote>
<p>When I saw someone use patch for the first time he totally confused me by claiming that -p is short for the &#8220;patch level&#8221; which &#8211; as you can see above &#8211; is utter nonsense. It is probably short for prefix and the long form of it &#8211;strip actually means something entirely different.</p>
<p>It is essentially the number of slashes that are to be ignored, including the part of the path to the left of each ignored slash. A strip level of 0 does not modify the paths at all. A level of 1 ignores the path up to and including the first slash. Omitting the p parameter causes patch to ignore the complete paths and only look at the file names.</p>
<p>If a patch without specified strip level doesn&#8217;t work then you will have to take a look at the patch file and figure out how much of the paths you need to ignore so that these paths fit with the situation on your own file system. In our example above (with the original and changed folders) we could have used -p1 to have patch ignore the relative paths, but it seems to do that by itself.</p>
<h3>Creating Patches from Repositories</h3>
<p>Above we discussed one way to create diffs that can be used for patches by having two versions of your files in two folders and diff these two. This typically suites those people who have not yet warmed to the use of source code management systems (SCM) like git or Subversion.</p>
<p>In an SCM you don&#8217;t have multiple copies of each file, instead you have only one current version of the source code in the project directory and all previous versions are somehow hidden from view, but can be retrieved. In git this versions are called &#8220;commits&#8221; in Subversion &#8220;revisions&#8221;.</p>
<p>For the sake of trying it out, let&#8217;s create an empty Xcode project with a git repo. On the dialog where you specify the folder for the project you can set a checkbox to have Xcode also put it under version control.</p>
<p><a href="http://www.cocoanetics.com/files/Bildschirmfoto-2011-12-27-um-09.13.00.png"><img class="alignnone size-full wp-image-5773" title="Xcode creating local git repository" src="http://www.cocoanetics.com/files/Bildschirmfoto-2011-12-27-um-09.13.00.png" alt="" width="585" height="137" /></a></p>
<p>It is probably an oversight in Xcode but if you create the project like this the first commit is being done for you with comment &#8220;Initial Commit&#8221;, however there are changes to the project file adding a &#8220;lastKnownFileType&#8221; to the project.pbxproj &#8211; which is contained in the xcodeproj bundle &#8211; that causes the project file to show as modified if you do &#8220;git status&#8221;.</p>
<p>To get to a clean starting state for the project I go to the folder where I created the project and do an additional commit.</p>

<div class="wp_codebox"><table><tr id="p5756243"><td class="code" id="p5756code243"><pre class="sh" style="font-family:monospace;">cd ~/scmtest
git status
git commit -a
git log</pre></td></tr></table></div>

<p>I have vi set up as my editor so on the file that opens from the commit I enter some comment and then ESC : w q to save and finish the commit. The git log now shows no uncommitted changes, two commits and two untracked files containing some user workspace settings which you probably don&#8217;t need or want in your repo.</p>
<p>Now let&#8217;s modify some code. For this test I just added an NSLog into the app delegate file. What&#8217;s really interesting now is how to create a patch that contains the changes from our second commit to the current modified state of our working directory. Simple, really:</p>

<div class="wp_codebox"><table><tr id="p5756244"><td class="code" id="p5756code244"><pre class="sh" style="font-family:monospace;">git diff --no-prefix &amp;gt; diff.patch</pre></td></tr></table></div>

<p>We need the option to omit the prefix because otherwise git diff adds an &#8220;a&#8221; and a &#8220;b&#8221; prefix in the paths which never correspond to actual paths. Of course you can also apply patches that still contain the prefixes if you use the -p1 strip level.</p>
<p>Our patch now looks like this:</p>
<pre>diff --git scmtest/DTAppDelegate.m scmtest/DTAppDelegate.m
index 7730864..795fa6d 100644
--- scmtest/DTAppDelegate.m
+++ scmtest/DTAppDelegate.m
@@ -20,6 +20,8 @@

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
+    NSLog(@"Hello World");
+
     self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
     // Override point for customization after application launch.
     self.window.backgroundColor = [UIColor whiteColor];</pre>
<p>You can see the inserted lines prefixed with plus, also there are a couple of lines of code before and after the insertion so that patch can find the place even when there have been other modifications to the file that changed the line numbers.</p>
<p>A simple git diff always contains all modifications made on the latest commit. To test this patch we discard our changes and see that we ended up on the second commit.</p>

<div class="wp_codebox"><table><tr id="p5756245"><td class="code" id="p5756code245"><pre class="sh" style="font-family:monospace;">git reset --hard
git log</pre></td></tr></table></div>

<p>Then we apply the patch, we need a strip level of zero so that the relative paths are used as they are.</p>

<div class="wp_codebox"><table><tr id="p5756246"><td class="code" id="p5756code246"><pre class="sh" style="font-family:monospace;">patch -p0 &amp;lt; diff.patch
git status</pre></td></tr></table></div>

<p>After this patch we see that the changes appeared again.</p>
<p>You can also create a patch between any two commits by specifying the commit identifiers as parameters. You can get the identifiers from git log.</p>

<div class="wp_codebox"><table><tr id="p5756247"><td class="code" id="p5756code247"><pre class="sh" style="font-family:monospace;">git log
git diff 92cef602e685970e6d4316cd383217d39d169b89 ec24c6d3435a2ae9ddaabd76f958561e86f9f02e &amp;gt; b.patch</pre></td></tr></table></div>

<p>Finally let&#8217;s also see how the same can be gotten from an SVN repo. Same technique:</p>

<div class="wp_codebox"><table><tr id="p5756248"><td class="code" id="p5756code248"><pre class="sh" style="font-family:monospace;">svn status
svn diff &amp;gt; diff.patch</pre></td></tr></table></div>

<p>Between two specific revisions the same is possible. Subversion numbers revisions incrementally instead of with identifiers as git does. So the command for the changes from a specific version to the next is this:</p>

<div class="wp_codebox"><table><tr id="p5756249"><td class="code" id="p5756code249"><pre class="sh" style="font-family:monospace;">svn diff -r 126:127 &amp;gt; c.patch</pre></td></tr></table></div>

<p>Contrary to git the diff command for svn does not prefix the file paths, instead the revision info is contained in brackets after the files which is ignored by patch.</p>
<h3>Conclusion</h3>
<p>Knowing how to create and apply patches is a great skill to have as a programmer. So the next time you find that you want to precisely communicate what changes you made in somebody else&#8217;s code you should send them a patch instead of an email containing line numbers and code fragments.</p>
<p>And if they don&#8217;t know what to do with that, also send them a link to this here tutorial. <img src='http://www.cocoanetics.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>PS: AlBlue points out that on git your can also directly <a href="http://alblue.bandlem.com/2011/12/git-tip-of-week-patches-by-email.html">send patches via e-mail</a>. Those even include your commit messages and identity.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5756&amp;md5=18ffcfd2b59faa866bec2b5a561fd4a5" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/12/how-to-make-and-apply-patches/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F12%2Fhow-to-make-and-apply-patches%2F&amp;language=en_GB&amp;category=text&amp;title=How+to+Make+and+Apply+Patches&amp;description=Sometimes+you+want+to+tell+somebody+how+you+fixed+a+problem+in+their+code%2C+but+for+some+reason+the+code+is+not+on+github+so+you+cannot+send+them+a...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Command Line Tools Tutorial (1)</title>
		<link>http://www.cocoanetics.com/2011/12/command-line-tools-tutorial-1/</link>
		<comments>http://www.cocoanetics.com/2011/12/command-line-tools-tutorial-1/#comments</comments>
		<pubDate>Sun, 11 Dec 2011 09:39:32 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5721</guid>
		<description><![CDATA[Honestly I was very much excited when I found that I can use my current knowledge of Objective-C and Foundation classes like NSString to also build nifty little tools. Previously I had to resort to bash script to perform one-off operations on files that where too tedious to do manually. But knowing what I am going to show you in this article will enable you to also write these littler helpers. I believe that beginners should rather start with writing a couple of command line tools before diving into building user interface driven apps. Commend line tools are linear and thus their function is easier to grasp. They are more akin to &#8220;functional programming&#8221; then &#8220;object oriented programming&#8221; if you will. I am going to show you what goes into building a simple command line tool and you be the judge whether you agree with my assessment. &#160; First we need a purpose for our tool. It just so happens that I have a great idea! Purpose: Join Several Files in a Structure Somebody handed me a set of all the Localizable.strings files from Apple&#8217;s built-in apps.  Those are divided by app and there you have one lproj sub-folder per language. I want to join all of these together in a big file so that I want to look up one translation I get all languages at the same time. The strings files themselves are binary property lists, basically a big NSDictionary each. That&#8217;s the same format that they get converted to if you build your app. Xcode takes each text strings file, omits the comment and packs them into the bplist format for faster loading. Before you set out to coding anything it is a good idea to reflect on which steps we think we require to achieve our goal: Produce a command line utility that can be called from the terminal and passed one directory as parameters. Iterate through the directories and get the contained files Open each file ending in .strings as dictionary Assemble in memory the tokens contained in each dictionary in a way that will facilitate generating the output we require Ok, let&#8217;s get to it. Step 1: Command Line Tool with Parameters We create a new project with the &#8220;Command Line Tool&#8221; from the Mac OS X/Application category. Under &#8220;Type&#8221; we see a couple of different templates. We want to use the one that says &#8220;Foundation&#8221; because this gives us all the Objective-C classes we know and love, like NSArray, NSString etc. Let&#8217;s also make it an ARC project so we don&#8217;t have to worry about memory management. I called my tool stringsextract. As with all C-based applications the starting point for the program is in the main function which you can find in main.m. int main &#40;int argc, const char * argv&#91;&#93;&#41; &#123; @autoreleasepool &#123; // insert code here... NSLog&#40;@&#34;Hello, World!&#34;&#41;; &#125; return 0; &#125; If it weren&#8217;t for the autorelease pool this would look like a very normal C-function. In objc methods generally are either class (+) or instance methods (-). In c functions are standing alone. This function main has an int as return value. If the program runs without error you want it to return 0, otherwise you want it to return something else, like 1. It has two parameters argc and argv. The first (argument count) is the number of parameters contained in the second (argument values). Int is just a number, but the second looks a bit more completed to the untrained eye. It is an array of char pointers. Since in c arrays are same as pointers you sometimes see this also written as char **argv, because in essence it is a pointer to a pointer to a char. Arrays in C are not secured against being overrun which is why we need the argc. Otherwise we would have no way of knowing how many entries this array has. C-style arrays are just some memory where the elements are in sequential order. To access the nth item, you use array[n-1] and the compiler will convert that into the correct memory address. (Note: in c indexes begin with 0) Another thing to know about argc/argv is that there is always at least one parameter at index 0: the name and path of the executable. So even if you call this program without any parameters on the command line argc will be 1 and there will be a value in argv[0]. The next tricky thing besides having to deal with a c-style array is that we also have to know c-style strings to make sense of the argument values. I told you above that an array is just a bunch of items. C-strings are just a bunch of characters where the last one is a binary zero, aka &#8216;\0&#8242;, to [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/12/command-line-tools-tutorial-1/"></g:plusone></div><p>Honestly I was very much excited when I found that I can use my current knowledge of Objective-C and Foundation classes like NSString to also build nifty little tools. Previously I had to resort to bash script to perform one-off operations on files that where too tedious to do manually. But knowing what I am going to show you in this article will enable you to also write these littler helpers.</p>
<p>I believe that beginners should rather start with writing a couple of command line tools before diving into building user interface driven apps. Commend line tools are linear and thus their function is easier to grasp. They are more akin to &#8220;functional programming&#8221; then &#8220;object oriented programming&#8221; if you will.</p>
<p>I am going to show you what goes into building a simple command line tool and you be the judge whether you agree with my assessment.</p>
<p><span id="more-5721"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>First we need a purpose for our tool. It just so happens that I have a great idea!</p>
<h3>Purpose: Join Several Files in a Structure</h3>
<p>Somebody handed me a set of all the Localizable.strings files from Apple&#8217;s built-in apps.  Those are divided by app and there you have one lproj sub-folder per language. I want to join all of these together in a big file so that I want to look up one translation I get all languages at the same time.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-12-10-at-4.51.34-PM.png"><img class="alignnone size-full wp-image-5722" title="The Input" src="http://www.cocoanetics.com/files/Screen-Shot-2011-12-10-at-4.51.34-PM.png" alt="" width="514" height="378" /></a></p>
<p>The strings files themselves are binary property lists, basically a big NSDictionary each. That&#8217;s the same format that they get converted to if you build your app. Xcode takes each text strings file, omits the comment and packs them into the bplist format for faster loading.</p>
<h3><span class="Apple-style-span" style="font-size: 13px; font-weight: normal;">Before you set out to coding anything it is a good idea to reflect on which steps we think we require to achieve our goal:</span></h3>
<ol>
<li>Produce a command line utility that can be called from the terminal and passed one directory as parameters.</li>
<li>Iterate through the directories and get the contained files</li>
<li>Open each file ending in .strings as dictionary</li>
<li>Assemble in memory the tokens contained in each dictionary in a way that will facilitate generating the output we require</li>
</ol>
<p>Ok, let&#8217;s get to it.</p>
<h3>Step 1: Command Line Tool with Parameters</h3>
<p>We create a new project with the &#8220;Command Line Tool&#8221; from the Mac OS X/Application category. Under &#8220;Type&#8221; we see a couple of different templates. We want to use the one that says &#8220;Foundation&#8221; because this gives us all the Objective-C classes we know and love, like NSArray, NSString etc. Let&#8217;s also make it an ARC project so we don&#8217;t have to worry about memory management. I called my tool <em>stringsextract</em>.</p>
<p>As with all C-based applications the starting point for the program is in the main function which you can find in main.m.</p>

<div class="wp_codebox"><table><tr id="p5721271"><td class="code" id="p5721code271"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">int</span> main <span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> argc, <span style="color: #a61390;">const</span> <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span> argv<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
    @autoreleasepool <span style="color: #002200;">&#123;</span>
        <span style="color: #11740a; font-style: italic;">// insert code here...</span>
        NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Hello, World!&quot;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #a61390;">return</span> <span style="color: #2400d9;">0</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>If it weren&#8217;t for the autorelease pool this would look like a very normal C-function. In objc methods generally are either class (+) or instance methods (-). In c functions are standing alone.</p>
<p>This function main has an int as return value. If the program runs without error you want it to return 0, otherwise you want it to return something else, like 1.</p>
<p>It has two parameters argc and argv. The first (argument count) is the number of parameters contained in the second (argument values). Int is just a number, but the second looks a bit more completed to the untrained eye. It is an array of char pointers. Since in c arrays are same as pointers you sometimes see this also written as char **argv, because in essence it is a pointer to a pointer to a char.</p>
<p>Arrays in C are not secured against being overrun which is why we need the argc. Otherwise we would have no way of knowing how many entries this array has. C-style arrays are just some memory where the elements are in sequential order. To access the nth item, you use array[n-1] and the compiler will convert that into the correct memory address. (Note: in c indexes begin with 0)</p>
<p>Another thing to know about argc/argv is that there is always at least one parameter at index 0: the name and path of the executable. So even if you call this program without any parameters on the command line argc will be 1 and there will be a value in argv[0].</p>
<p>The next tricky thing besides having to deal with a c-style array is that we also have to know c-style strings to make sense of the argument values. I told you above that an array is just a bunch of items. C-strings are just a bunch of characters where the last one is a binary zero, aka &#8216;\0&#8242;, to delimit the string. So whenever you see char * this could either be a pointer to one character or it could be a pointer to the first character of a string.</p>
<p>Since we want to use Foundation constructs for our program we want to convert all c-stuff to the more intelligent variants like NSString, by means of stringWithUTF8String.</p>
<p>As a first experiment let&#8217;s output all the arguments. We do a normal for loop beginning with 0, convert each argument to an NSString and log it.</p>

<div class="wp_codebox"><table><tr id="p5721272"><td class="code" id="p5721code272"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> i<span style="color: #002200;">=</span><span style="color: #2400d9;">0</span>; i&lt;argc; i<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>str <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> stringWithUTF8String<span style="color: #002200;">:</span>argv<span style="color: #002200;">&#91;</span>i<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;argv[%d] = '%@'&quot;</span>, i, str<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>If you hit Run now you will see the following output on the console:</p>

<div class="wp_codebox"><table><tr id="p5721273"><td class="code" id="p5721code273"><pre class="sh" style="font-family:monospace;">2011-12-11 09:21:58.636 stringsextract[18003:707] argv[0] = '/Users/oliver/Library/Developer/Xcode/DerivedData/stringsextract-dlkdghopgfoghoanjhmahhrlotsp/Build/Products/Debug/stringsextract'</pre></td></tr></table></div>

<p>So really what I told you is true, the parameter at index 0 has the path of our binary.</p>
<p>How can we test our program while we are still working on it? Of course you could open a terminal and run it by hand:</p>

<div class="wp_codebox"><table><tr id="p5721274"><td class="code" id="p5721code274"><pre class="sh" style="font-family:monospace;">iair:~ oliver$ cd /Users/oliver/Library/Developer/Xcode/DerivedData/stringsextract-dlkdghopgfoghoanjhmahhrlotsp/Build/Products/Debug/
iair:Debug oliver$ ./stringsextract bla
2011-12-11 09:25:03.357 stringsextract[18017:707] argv[0] = './stringsextract'
2011-12-11 09:25:03.363 stringsextract[18017:707] argv[1] = 'bla'</pre></td></tr></table></div>

<p>You see how I changed into the Debug output directory and executed the program there passing one extra parameter. The dot slash is necessary to tell the shell that it should take the stringsextract binary right there in the current directory. Otherwise it would go off searching the set up system paths. You also see that argv[0] does not actually contain the absolute path, but always how it was called.</p>
<p>Now this works, but it might be a bit tedious to work with while we are still testing and debugging our tool. Fortunately Xcode allows us to specify command line arguments in the schema. If one argument contains whitespace you need to put it in quotes.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-12-11-at-9.41.41-AM.png"><img src="http://www.cocoanetics.com/files/Screen-Shot-2011-12-11-at-9.41.41-AM.png" alt="" title="Specifying command line arguments in Xcode" width="700" height="469" class="alignnone size-full wp-image-5727" /></a></p>
<p>If we hit Run like this then we can also debug and step through our code as if we had passed this parameter on the command line ourselves.</p>
<p>As a final step in this chapter let us add a usage text which is to be output if somebody calls this program of ours without the required one parameter.</p>

<div class="wp_codebox"><table><tr id="p5721275"><td class="code" id="p5721code275"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// one parameter is required</span>
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>argc<span style="color: #002200;">!=</span><span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
    <span style="color: #11740a; font-style: italic;">// output usage</span>
    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #a61390;">printf</span></a><span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">&quot;Usage: stringsextract &lt;dir&gt;<span style="color: #2400d9;">\n</span>&quot;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// leave with code 1</span>
    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/exit.html"><span style="color: #a61390;">exit</span></a><span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Note the use of the c-function printf which unlike NSLog just outputs the stuff we want and no extra stuff.</p>
<p>Now we&#8217;re set to move to Step 2.</p>
<h3>Step 2: Getting the Files</h3>
<p>Foundation gives us some awesome utilities when working with the file system, most notably NSFileManager which groups together most of them. We have our parameter specifying an absolute path. So next we need to list the .app bundles contained in there.</p>
<p>Usually you would use [NSFileManager defaultManager] to get a file manager instance. Only if you need to set a call-back delegate you would go about alloc/init&#8217;ing it.</p>
<p>So following our check for the existence of at least one parameter we add:</p>

<div class="wp_codebox"><table><tr id="p5721276"><td class="code" id="p5721code276"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// convert path to NSString</span>
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>path <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> stringWithUTF8String<span style="color: #002200;">:</span>argv<span style="color: #002200;">&#91;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// get file manager</span>
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/"><span style="color: #400080;">NSFileManager</span></a> <span style="color: #002200;">*</span>fileManager <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/"><span style="color: #400080;">NSFileManager</span></a> defaultManager<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// get directory contents</span>
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/"><span style="color: #400080;">NSError</span></a> <span style="color: #002200;">*</span>error;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span>contents <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>fileManager contentsOfDirectoryAtPath<span style="color: #002200;">:</span>path
                                                     error<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// handle error</span>
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>contents<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #a61390;">printf</span></a><span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">&quot;%s<span style="color: #2400d9;">\n</span>&quot;</span>,<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>error localizedDescription<span style="color: #002200;">&#93;</span> UTF8String<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/exit.html"><span style="color: #a61390;">exit</span></a><span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>, contents<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>This converts the parameter to an NSString, sets up a file manager and then gets the contents of the specified path. If this is successful then there is a non-nil value in contents. If not then error will point to a new NSError instance which gives us a nice localized description to tell the user. Again we use printf because we want the direct output. UTF8String is the method to get from an objective-C NSString to back to a regular C-string which is required by the %s print format.</p>
<p>The NSLog at the bottom is just temporary so that we can see if we indeed got a result. And so we did.</p>

<div class="wp_codebox"><table><tr id="p5721277"><td class="code" id="p5721code277"><pre class="sh" style="font-family:monospace;">2011-12-11 10:08:47.023 stringsextract[18231:707] (
    &quot;.DS_Store&quot;,
    &quot;AppStore.app&quot;,
    &quot;Calculator.app&quot;,
    &quot;Camera.app&quot;,
    &quot;Compass.app&quot;,
    &quot;Contacts~iphone.app&quot;,
    &quot;Game Center~iphone.app&quot;,
    &quot;Maps~iphone.app&quot;,
    &quot;MobileCal.app&quot;,
    &quot;MobileMail.app&quot;,
    &quot;MobileNotes.app&quot;,
    &quot;MobilePhone.app&quot;,
    &quot;MobileSafari.app&quot;,
    &quot;MobileSlideShow.app&quot;,
    &quot;MobileSMS.app&quot;,
    &quot;MobileStore.app&quot;,
    &quot;Music~iphone.app&quot;,
    &quot;Nike.app&quot;,
    &quot;Preferences.app&quot;,
    &quot;Reminders.app&quot;,
    &quot;Setup.app&quot;,
    &quot;Stocks.app&quot;,
    &quot;Videos.app&quot;,
    &quot;Weather.app&quot;,
    &quot;YouTube.app&quot;
)
Program ended with exit code: 0</pre></td></tr></table></div>

<p> We also see that there is one entry that we want to ignore later on, the &#8220;.DS_Store&#8221;. So let&#8217;s filter out everything that does not end in .app as I showed in a <a href="http://www.cocoanetics.com/2010/03/directories-temp-cache-documents/" title="Directories: Temp, Cache, Documents">previous post</a>.</p>
<p>Now we need to iterate through the array of app paths and get the contents of these, filtering for lproj. Since the contents are without the full path we need to concatenate the individual names with the path.</p>

<div class="wp_codebox"><table><tr id="p5721278"><td class="code" id="p5721code278"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// filter</span>
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span>filter <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> arrayWithObject<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;app&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// execute filter in place</span>
contents <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>contents pathsMatchingExtensions<span style="color: #002200;">:</span>filter<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// iterate through .app</span>
<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>oneApp <span style="color: #a61390;">in</span> contents<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
    <span style="color: #11740a; font-style: italic;">// make full path</span>
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>appPath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>path stringByAppendingPathComponent<span style="color: #002200;">:</span>oneApp<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// get contents, ignore error</span>
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span>appContents <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>fileManager contentsOfDirectoryAtPath<span style="color: #002200;">:</span>appPath
                                                            error<span style="color: #002200;">:</span><span style="color: #a61390;">NULL</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;app: %@, %@&quot;</span>, oneApp, appContents<span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Again we have a bunch of files that we one and one that we don&#8217;t, in this case I have have a _CodeResources. Granted I could have removed these by hand but we&#8217;re writing this program here to be smart and save us manual labor. So we code around that just the same.</p>
<p>Rinse and repeat. We end up with three loops, one for the apps, one for the lprojs and one for the strings.</p>

<div class="wp_codebox"><table><tr id="p5721279"><td class="code" id="p5721code279"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">int</span> main <span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> argc, <span style="color: #a61390;">const</span> <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span> argv<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
    @autoreleasepool 
    <span style="color: #002200;">&#123;</span>
        <span style="color: #11740a; font-style: italic;">// one parameter is required</span>
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>argc<span style="color: #002200;">!=</span><span style="color: #2400d9;">2</span><span style="color: #002200;">&#41;</span>
        <span style="color: #002200;">&#123;</span>
            <span style="color: #11740a; font-style: italic;">// output usage</span>
            <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #a61390;">printf</span></a><span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">&quot;Usage: stringsextract &lt;dir&gt;<span style="color: #2400d9;">\n</span>&quot;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
            <span style="color: #11740a; font-style: italic;">// leave with code 1</span>
            <a href="http://www.opengroup.org/onlinepubs/009695399/functions/exit.html"><span style="color: #a61390;">exit</span></a><span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
        <span style="color: #002200;">&#125;</span>
&nbsp;
        <span style="color: #11740a; font-style: italic;">// convert path to NSString</span>
        <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>path <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> stringWithUTF8String<span style="color: #002200;">:</span>argv<span style="color: #002200;">&#91;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #11740a; font-style: italic;">// get file manager</span>
        <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/"><span style="color: #400080;">NSFileManager</span></a> <span style="color: #002200;">*</span>fileManager <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/"><span style="color: #400080;">NSFileManager</span></a> defaultManager<span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #11740a; font-style: italic;">// get directory contents</span>
        <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/"><span style="color: #400080;">NSError</span></a> <span style="color: #002200;">*</span>error;
        <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span>contents <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>fileManager contentsOfDirectoryAtPath<span style="color: #002200;">:</span>path
                                                             error<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #11740a; font-style: italic;">// handle error</span>
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>contents<span style="color: #002200;">&#41;</span>
        <span style="color: #002200;">&#123;</span>
            <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #a61390;">printf</span></a><span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">&quot;%s<span style="color: #2400d9;">\n</span>&quot;</span>,<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>error localizedDescription<span style="color: #002200;">&#93;</span> UTF8String<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
            <a href="http://www.opengroup.org/onlinepubs/009695399/functions/exit.html"><span style="color: #a61390;">exit</span></a><span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
        <span style="color: #002200;">&#125;</span>
&nbsp;
        <span style="color: #11740a; font-style: italic;">// filter</span>
        <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span>filter <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> arrayWithObject<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;app&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #11740a; font-style: italic;">// execute filter in place</span>
        contents <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>contents pathsMatchingExtensions<span style="color: #002200;">:</span>filter<span style="color: #002200;">&#93;</span>;
&nbsp;
        <span style="color: #11740a; font-style: italic;">// iterate through .app</span>
        <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>oneApp <span style="color: #a61390;">in</span> contents<span style="color: #002200;">&#41;</span>
        <span style="color: #002200;">&#123;</span>
            <span style="color: #11740a; font-style: italic;">// make full path</span>
            <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>appPath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>path stringByAppendingPathComponent<span style="color: #002200;">:</span>oneApp<span style="color: #002200;">&#93;</span>;
&nbsp;
            <span style="color: #11740a; font-style: italic;">// get contents, ignore error</span>
            <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span>appContents <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>fileManager contentsOfDirectoryAtPath<span style="color: #002200;">:</span>appPath
                                                                    error<span style="color: #002200;">:</span><span style="color: #a61390;">NULL</span><span style="color: #002200;">&#93;</span>;
&nbsp;
            <span style="color: #11740a; font-style: italic;">// new filter</span>
            filter <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> arrayWithObject<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;lproj&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
            <span style="color: #11740a; font-style: italic;">// execute filter in place</span>
            appContents <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>appContents pathsMatchingExtensions<span style="color: #002200;">:</span>filter<span style="color: #002200;">&#93;</span>;
&nbsp;
            <span style="color: #11740a; font-style: italic;">// iterate through .lproj = one language</span>
            <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>oneLang <span style="color: #a61390;">in</span> appContents<span style="color: #002200;">&#41;</span>
            <span style="color: #002200;">&#123;</span>
                <span style="color: #11740a; font-style: italic;">// make full path</span>
                <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>langPath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>appPath stringByAppendingPathComponent<span style="color: #002200;">:</span>oneLang<span style="color: #002200;">&#93;</span>;
&nbsp;
                <span style="color: #11740a; font-style: italic;">// get contents, ignore error</span>
                <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span>langContents <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>fileManager contentsOfDirectoryAtPath<span style="color: #002200;">:</span>langPath
                                                                         error<span style="color: #002200;">:</span><span style="color: #a61390;">NULL</span><span style="color: #002200;">&#93;</span>;
&nbsp;
                <span style="color: #11740a; font-style: italic;">// new filter</span>
                filter <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> arrayWithObject<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;strings&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
                <span style="color: #11740a; font-style: italic;">// execute filter in place</span>
                langContents <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>langContents pathsMatchingExtensions<span style="color: #002200;">:</span>filter<span style="color: #002200;">&#93;</span>;
&nbsp;
&nbsp;
                <span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>oneStrings <span style="color: #a61390;">in</span> langContents<span style="color: #002200;">&#41;</span>
                <span style="color: #002200;">&#123;</span>
                    <span style="color: #11740a; font-style: italic;">// make full path</span>
                    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>stringsPath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>langPath stringByAppendingPathComponent<span style="color: #002200;">:</span>oneStrings<span style="color: #002200;">&#93;</span>;
&nbsp;
                    <span style="color: #11740a; font-style: italic;">// do work here</span>
                    NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>, stringsPath<span style="color: #002200;">&#41;</span>;
                <span style="color: #002200;">&#125;</span>
            <span style="color: #002200;">&#125;</span>
        <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#125;</span>
    <span style="color: #a61390;">return</span> <span style="color: #2400d9;">0</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>If this code makes your stomach churn then this is because this more and more turns into spaghetti code. This can still be fine for a one-off tool, but should be avoided if you plan to hand out this tool for others to use. </p>
<p>For one thing I would add a category to NSFileManager that does the listing, filtering and full-path-assembling in one step. Or possibly even go one further to have the working code in a block and have this category iterate over the strings files.</p>
<p>This we will be exploring in the next installment of this two part tutorial.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5721&amp;md5=0a15d30ad86a723a0b7ae12798dadd0d" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/12/command-line-tools-tutorial-1/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F12%2Fcommand-line-tools-tutorial-1%2F&amp;language=en_GB&amp;category=text&amp;title=Command+Line+Tools+Tutorial+%281%29&amp;description=Honestly+I+was+very+much+excited+when+I+found+that+I+can+use+my+current+knowledge+of+Objective-C+and+Foundation+classes+like+NSString+to+also+build+nifty+little+tools.+Previously...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Sub-Projects in Xcode</title>
		<link>http://www.cocoanetics.com/2011/12/sub-projects-in-xcode/</link>
		<comments>http://www.cocoanetics.com/2011/12/sub-projects-in-xcode/#comments</comments>
		<pubDate>Fri, 02 Dec 2011 12:24:19 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5700</guid>
		<description><![CDATA[A very interesting yet very undocumented functionality of Xcode is that you can have sub-projects in your project tree. You can add an xcodeproj to your project and link to this project&#8217;s output. This is exceptionally useful if you are developing some functionality in a contained project and now want to access this polished functionality from another project. Like for example you want to add to your app the capability of accepting HTML code copied from Safari and use my DTWebArchive classes for that. You could either copy all classes to your project, build two libraries (one for Simulator and one for Device, or lipo these two together), or build a static universal framework. Or there is an option number 4 which I want to tell you about in this post. This option does neither copy source code nor does it involve building something upfront. &#160; Note that Xcode 4.2 might cause you a bit of trouble until this works right. Some people told me that they did what I am about to describe in Xcode 3 to get it working. One way or the other this here should work, and if it doesn&#8217;t work for you then &#8220;you&#8217;re holding it wrong&#8221;. Sub-Projects, An Overlooked Option This is the first case where I myself am using sub-projects. My DTRichTextEditor framework is making heavy use of my two open source projects. This is how the project tree looks on my machine: The file system structure and the group structure are more or less identical. I have a folder Externals that contains clones of these two GitHub projects. When you add an xcodeproj to your project then it will show up as shown in the picture, allowing you to browse the source code contained in this sub-project as well. Better yet, when you&#8217;re debugging you get to step through the sub-project&#8217;s code as if it where local. There are several caveats, besides sometimes having to restart Xcode several times for the project trees to show up. Xcode seems to take objection to you having the sub-project also opened at the same time. If you did that you will get an error message that the consistency of the sub-project cannot be verified. So make sure you don&#8217;t have the sub project open at the same time. You can edit the code from within the larger project anyway. Preparing the Sub-Project For being able to use an xcodeproj like shown above you need a couple of things, let me walk you through these. You need at least one target that builds an iOS static library. Go to your project root and add such a target. Then pick all the headers and implementation files that you want to be part of this library. I like to name the target different from the product. I want the target to be called &#8220;Static Library&#8221; and then I go into the build settings and call the product DTWebArchive, resulting in a product libDTWebArchive.a showing up under Products. You do not need to modify the header use which can be project, private or public. Changing it from the default project just copies these headers into the product output path which is of little use. You might also want to adjust the name of the Scheme, or auto generate schemes for your targets. These schemes are just a convenience for you personally, they are not even saved in the xcodeproj file. Make sure that your library builds without warnings or errors. Note that if you didn&#8217;t select any source files then the libtool will fail, too, without any useful error message. That happened to me on several occasions. Adding the Sub-Project Once you are satisfied with the static library close this project and open the other one that should contain it. Depending on how you work you could either keep all your projects in the same location next to each other or have the larger project actually also contain the smaller one. It&#8217;s up to you. I recommend the second option because your file system structure might be different from somebody else building this project. If you use absolute paths, or even relative ones pointing outside of the project root folder then you are asking for trouble. When adding the sub-project you don&#8217;t need to select it to be a member of any targets just yet. Best if you just drag the xcodeproj from Finder into the project. Next you need to add the path to look for the sub-project&#8217;s headers in to your build settings. You cannot add the .h files to your main project, but you can tell the compiler where it can find them. Specify the path relative to your project&#8217;s root folder. I chose recursive because I have multiple sub-projects and this way I only need [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/12/sub-projects-in-xcode/"></g:plusone></div><p>A very interesting yet very undocumented functionality of Xcode is that you can have sub-projects in your project tree. You can add an xcodeproj to your project and link to this project&#8217;s output.</p>
<p>This is exceptionally useful if you are developing some functionality in a contained project and now want to access this polished functionality from another project. Like for example you want to add to your app the capability of accepting HTML code copied from Safari and use my <a href="http://cocoanetics.github.com/DTWebArchive/">DTWebArchive</a> classes for that. You could either copy all classes to your project, build two libraries (one for Simulator and one for Device, or lipo these two together), or build a static universal framework.</p>
<p>Or there is an option number 4 which I want to tell you about in this post. This option does neither copy source code nor does it involve building something upfront.</p>
<p><span id="more-5700"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<div class="textwidget">
<p>&nbsp;</p>
</div></div>
</div>
<p>Note that Xcode 4.2 might cause you a bit of trouble until this works right. Some people told me that they did what I am about to describe in Xcode 3 to get it working. One way or the other this here should work, and if it doesn&#8217;t work for you then &#8220;you&#8217;re holding it wrong&#8221;. <img src='http://www.cocoanetics.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<h3>Sub-Projects, An Overlooked Option</h3>
<p>This is the first case where I myself am using sub-projects. My DTRichTextEditor framework is making heavy use of my two open source projects. This is how the project tree looks on my machine:</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-12-02-at-11.28.14-AM.png"><img class="alignnone size-full wp-image-5701" title="Two Sub-Projects" src="http://www.cocoanetics.com/files/Screen-Shot-2011-12-02-at-11.28.14-AM.png" alt="" width="370" height="496" /></a></p>
<p>The file system structure and the group structure are more or less identical. I have a folder Externals that contains clones of these two GitHub projects. When you add an xcodeproj to your project then it will show up as shown in the picture, allowing you to browse the source code contained in this sub-project as well. Better yet, when you&#8217;re debugging you get to step through the sub-project&#8217;s code as if it where local.</p>
<p>There are several caveats, besides sometimes having to restart Xcode several times for the project trees to show up. Xcode seems to take objection to you having the sub-project also opened at the same time. If you did that you will get an error message that the consistency of the sub-project cannot be verified. So make sure you don&#8217;t have the sub project open at the same time. You can edit the code from within the larger project anyway.</p>
<h3>Preparing the Sub-Project</h3>
<p>For being able to use an xcodeproj like shown above you need a couple of things, let me walk you through these.</p>
<p>You need at least one target that builds an iOS static library. Go to your project root and add such a target. Then pick all the headers and implementation files that you want to be part of this library.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-12-02-at-11.47.49-AM.png"><img class="alignnone size-full wp-image-5702" title="Making a static library" src="http://www.cocoanetics.com/files/Screen-Shot-2011-12-02-at-11.47.49-AM.png" alt="" width="608" height="455" /></a></p>
<p>I like to name the target different from the product. I want the target to be called &#8220;Static Library&#8221; and then I go into the build settings and call the product DTWebArchive, resulting in a product libDTWebArchive.a showing up under Products.</p>
<p>You do not need to modify the header use which can be project, private or public. Changing it from the default project just copies these headers into the product output path which is of little use. You might also want to adjust the name of the Scheme, or auto generate schemes for your targets. These schemes are just a convenience for you personally, they are not even saved in the xcodeproj file.</p>
<p>Make sure that your library builds without warnings or errors. Note that if you didn&#8217;t select any source files then the libtool will fail, too, without any useful error message. That happened to me on several occasions.</p>
<h3>Adding the Sub-Project</h3>
<p>Once you are satisfied with the static library close this project and open the other one that should contain it. Depending on how you work you could either keep all your projects in the same location next to each other or have the larger project actually also contain the smaller one. It&#8217;s up to you. I recommend the second option because your file system structure might be different from somebody else building this project. If you use absolute paths, or even relative ones pointing outside of the project root folder then you are asking for trouble.</p>
<p>When adding the sub-project you don&#8217;t need to select it to be a member of any targets just yet. Best if you just drag the xcodeproj from Finder into the project.</p>
<p>Next you need to add the path to look for the sub-project&#8217;s headers in to your build settings. You cannot add the .h files to your main project, but you can tell the compiler where it can find them. Specify the path relative to your project&#8217;s root folder. I chose recursive because I have multiple sub-projects and this way I only need to specify this setting once.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-12-02-at-1.00.55-PM.png"><img class="alignnone size-full wp-image-5704" title="Setting the header search path" src="http://www.cocoanetics.com/files/Screen-Shot-2011-12-02-at-1.00.55-PM.png" alt="" width="742" height="399" /></a></p>
<p>With this setup you can use the same import directives that you are used to.</p>
<p>You tell the linker to link against the static library target in the sub project. You set this up on the Build Phases tab, under &#8220;Link Binary With Libraries&#8221;. You probably want it to be &#8220;Required&#8221; for static libraries because we cannot build dynamic libraries (dylib) as Apple is using in their frameworks.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-12-02-at-1.04.22-PM.png"><img class="alignnone size-full wp-image-5705" title="Build Phases" src="http://www.cocoanetics.com/files/Screen-Shot-2011-12-02-at-1.04.22-PM.png" alt="" width="652" height="287" /></a></p>
<p>You also want to add the static library targets as dependencies for your app. This way the build system knows that it needs to rebuild the app object code if code in the dependency changes.</p>
<p>If you were only programming in c then that would be all, but since we are coding in Objective-C (and possible use ARC) there are &#8220;Other Linker Flags&#8221; we need to add:</p>
<ul>
<li><strong>-ObjC</strong> because otherwise the linker does not properly load your classes</li>
<li><strong>-all_load</strong> if you have categories in the library, because otherwise those are not loaded</li>
<li><strong>-fobjc-arc</strong> if you are linking against a library built with ARC from an app that does not yet use ARC</li>
</ul>
<p>Actually the first two are pretty standard, so if you have ever done anything with static libraries before you already know about these.</p>
<h3>Conclusion</h3>
<p>You see, there is not very much too it and you can stop copying your reused source code all over the place. Better you put it in your own foundation framework (as I have begun with <a href="http://cocoanetics.github.com/DTFoundation/">DTFoundation</a>), <a title="Amazing Apple-like Documentation" href="http://www.cocoanetics.com/2011/11/amazing-apple-like-documentation/">document it</a> and add the appropriate unit tests. This way any new methods or polishing benefits all your apps instead of just the current one.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5700&amp;md5=5a17535bad47014e580999b5d92a45d5" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/12/sub-projects-in-xcode/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;popout=1&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F12%2Fsub-projects-in-xcode%2F&amp;language=en_GB&amp;category=text&amp;title=Sub-Projects+in+Xcode&amp;description=A+very+interesting+yet+very+undocumented+functionality+of+Xcode+is+that+you+can+have+sub-projects+in+your+project+tree.+You+can+add+an+xcodeproj+to+your+project+and+link+to...&amp;tags=blog" type="text/html" />
	</item>
	</channel>
</rss>

