<?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>Fri, 03 Feb 2012 18:25:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>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. Label Buy an ad here Readability 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; [...]]]></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></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="p58875"><td class="code" id="p5887code5"><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="p58876"><td class="code" id="p5887code6"><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="p58877"><td class="code" id="p5887code7"><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="p58878"><td class="code" id="p5887code8"><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>0</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5887&amp;md5=4af7587e6b75dcc81ddd9ca30897f36d" 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. Label Buy an ad here Readability 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. # [...]]]></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></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="p585912"><td class="code" id="p5859code12"><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="p585913"><td class="code" id="p5859code13"><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="p585914"><td class="code" id="p5859code14"><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="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5859&amp;md5=450103b7bf2d416c4504c16e867994e4" 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. Label Buy an ad here Readability 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 [...]]]></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></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="p583424"><td class="code" id="p5834code24"><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="p583425"><td class="code" id="p5834code25"><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="p583426"><td class="code" id="p5834code26"><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="p583427"><td class="code" id="p5834code27"><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="p583428"><td class="code" id="p5834code28"><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="p583429"><td class="code" id="p5834code29"><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="p583430"><td class="code" id="p5834code30"><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="p583431"><td class="code" id="p5834code31"><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="p583432"><td class="code" id="p5834code32"><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>0</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5834&amp;md5=71505f45c772506d51675dd3c0636f33" 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. Label Buy an ad here Readability 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 [...]]]></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></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>0</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5825&amp;md5=2d7dee18cea6ddcc2a930d578c490b8e" 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. Label Buy an ad here Readability 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 [...]]]></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></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="p575645"><td class="code" id="p5756code45"><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="p575646"><td class="code" id="p5756code46"><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="p575647"><td class="code" id="p5756code47"><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="p575648"><td class="code" id="p5756code48"><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="p575649"><td class="code" id="p5756code49"><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="p575650"><td class="code" id="p5756code50"><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="p575651"><td class="code" id="p5756code51"><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="p575652"><td class="code" id="p5756code52"><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="p575653"><td class="code" id="p5756code53"><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="p575654"><td class="code" id="p5756code54"><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="p575655"><td class="code" id="p5756code55"><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="p575656"><td class="code" id="p5756code56"><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>1</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5756&amp;md5=18ffcfd2b59faa866bec2b5a561fd4a5" 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. Label Buy an ad here Readability 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 [...]]]></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></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="p572166"><td class="code" id="p5721code66"><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="p572167"><td class="code" id="p5721code67"><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="p572168"><td class="code" id="p5721code68"><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="p572169"><td class="code" id="p5721code69"><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="p572170"><td class="code" id="p5721code70"><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="p572171"><td class="code" id="p5721code71"><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="p572172"><td class="code" id="p5721code72"><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="p572173"><td class="code" id="p5721code73"><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="p572174"><td class="code" id="p5721code74"><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="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5721&amp;md5=0a15d30ad86a723a0b7ae12798dadd0d" 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. Label Buy an ad here Readability 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 [...]]]></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></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="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5700&amp;md5=5a17535bad47014e580999b5d92a45d5" type="text/html" />"
	</item>
		<item>
		<title>Submitting Your First Mac App Store App</title>
		<link>http://www.cocoanetics.com/2011/10/submitting-your-first-mac-app-store-app/</link>
		<comments>http://www.cocoanetics.com/2011/10/submitting-your-first-mac-app-store-app/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 19:01:26 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5635</guid>
		<description><![CDATA[I would say I have the process of submitting iOS apps down, I could probably do it blindfolded. Actually I HAVE done it blindfolded on several occasions guiding people over the phone on their very first submission. But today I am doing it for the first time on an app for the Mac App Store (aka MAS). Let&#8217;s see if I can see this through to a successful conclusion, or at least until the ball is out of my court and with the app review team. Label Buy an ad here Readability A couple of months ago we made a deal with BytePoets, a small software company based in Graz, Austria. At that time I had an idea for a Mac tool that would greatly simplify how you localize apps. But at the same time I was afraid of starting to code on OSX. I did not have the time to devote to this project to get up to speed myself, so I let them do the development. Publication and marketing of the app now falls to me. Certificates and Profiles So as the first step &#8211; I figured &#8211; I probably need a distribution certificate for the app. So I logged into the Mac Developer Center and went looking for the Mac equivalent of the provisioning portal. I found the &#8220;Developer Certificate Utility&#8221;, which sounded like what I needed. First thing to do there was to register an app ID. You choose an app bundle identifier similar as you would do on iOS, in reverse domain notation with the final part being the name of your app. Also you give the identifier a name or description so that you find it later. &#160; The second step is to confirm your input as you can only delete such identifiers from your account, but you will never be able to edit them. On the screen that follows you can configure iCloud and Apple Push Notification support for the app, but we didn&#8217;t need those at this time. On the Certificates tab I was confused to see a Mac App and a Mac Installer certificate already there. I didn&#8217;t recall creating these. So I ignored them for the time being and clicked the big blue button to request a new certificate. Then I felt at home again, you get a choice to create a developer or a distribution authority and just like on iOS you have to use the certificate assistant in your Keychain Access to get these. The assistant creates the private key in your keychain and you save the public key to a file. This you upload to Apple and they sign it. Then at the end of the process you download their result and it joins the private key in your keychain when you open it from your downloads folder. You have to create two distinct signing requests for a development and a distribution identity. The product of this is that you end up with 5 certificates on your keychain, the &#8220;iPhone Developer/Distribution&#8221; you have seen before, as well as two new ones titled &#8220;3rd Party Mac Application&#8221; and &#8220;Mac Developer&#8221;. Looks ok, if all 5 certificates have the private key dangling under it. On my first run through here I forgot about the second distribution profile for the MAS, you need to have both a Installer and Application certificate for that, where with iOS this is only one certificate. If you don&#8217;t get the Installer certificate then you will find that you cannot validate or submit apps, instead you get stuck with &#8220;Don&#8217;t sign package (No valid signing identities found)&#8221;. The third tap is titled Systems and looks to be the same as where you enter your iOS device IDs. For practice I went ahead and registered my MacBook Air. I didn&#8217;t know that even Macs had hardware device identifiers! You can find the one for your machine on the &#8220;About this Mac&#8221; and then look for &#8220;Hardware UUID&#8221;. Just like with iOS you are apparently limited to registering 100 such systems per year. Obviously this has to be only for testing purposes, like iCloud and Push Notifications, right? The fourth and last step is to titled Provisioning Profiles, again a concept we met in the iOS world. Again a big blue button leads to a selection between either Development or Production, where I believe the latter to mean the same as Distribution. For a Development profile you specify a name or description, choose the previously generated bundle identifier, select the systems that are allowed to run this and the developer certificate. For the Production profile I was presented with two Mac Application Distribution Signing Certificates, so I chose the one with a later expiration date. That must have been one of the two that I saw earlier, but [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/10/submitting-your-first-mac-app-store-app/"></g:plusone></div><p>I would say I have the process of submitting iOS apps down, I could probably do it blindfolded. Actually I HAVE done it blindfolded on several occasions guiding people over the phone on their very first submission.</p>
<p>But today I am doing it for the first time on an app for the Mac App Store (aka MAS). Let&#8217;s see if I can see this through to a successful conclusion, or at least until the ball is out of my court and with the app review team.</p>
<p><span id="more-5635"></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>A couple of months ago we made a deal with <a href="http://www.bytepoets.com/">BytePoets</a>, a small software company based in Graz, Austria. At that time I had an idea for a Mac tool that would greatly simplify how you localize apps. But at the same time I was afraid of starting to code on OSX. I did not have the time to devote to this project to get up to speed myself, so I let them do the development. Publication and marketing of the app now falls to me.</p>
<h3>Certificates and Profiles</h3>
<p>So as the first step &#8211; I figured &#8211; I probably need a distribution certificate for the app. So I logged into the Mac Developer Center and went looking for the Mac equivalent of the provisioning portal. I found the &#8220;Developer Certificate Utility&#8221;, which sounded like what I needed.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-4.13.19-PM.png"><img class="alignnone size-full wp-image-5636" title="Developer Certificate Utility" src="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-4.13.19-PM.png" alt="" width="215" height="180" /></a></p>
<p>First thing to do there was to<strong> register an app ID</strong>. You choose an app bundle identifier similar as you would do on iOS, in reverse domain notation with the final part being the name of your app. Also you give the identifier a name or description so that you find it later.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-4.17.55-PM.png"><img class="alignnone size-full wp-image-5637" title="Register Bundle ID" src="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-4.17.55-PM.png" alt="" width="444" height="286" /></a></p>
<p>&nbsp;</p>
<p>The second step is to confirm your input as you can only delete such identifiers from your account, but you will never be able to edit them.</p>
<p>On the screen that follows you can configure iCloud and Apple Push Notification support for the app, but we didn&#8217;t need those at this time.</p>
<p>On the Certificates tab I was confused to see a Mac App and a Mac Installer certificate already there. I didn&#8217;t recall creating these. So I ignored them for the time being and clicked the big blue button to request a new certificate.</p>
<p>Then I felt at home again, you get a choice to create a developer or a distribution authority and just like on iOS you have to use the certificate assistant in your Keychain Access to get these. The assistant creates the private key in your keychain and you save the public key to a file. This you upload to Apple and they sign it. Then at the end of the process you download their result and it joins the private key in your keychain when you open it from your downloads folder. You have to create two distinct signing requests for a development and a distribution identity.</p>
<p>The product of this is that you end up with 5 certificates on your keychain, the &#8220;iPhone Developer/Distribution&#8221; you have seen before, as well as two new ones titled &#8220;3rd Party Mac Application&#8221; and &#8220;Mac Developer&#8221;. Looks ok, if all 5 certificates have the private key dangling under it.</p>
<p>On my first run through here I forgot about the second distribution profile for the MAS, you need to have both a Installer and Application certificate for that, where with iOS this is only one certificate. If you don&#8217;t get the Installer certificate then you will find that you cannot validate or submit apps, instead you get stuck with &#8220;Don&#8217;t sign package (No valid signing identities found)&#8221;.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-7.31.33-PM.png"><img class="alignnone size-large wp-image-5646" title="5 certificates" src="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-7.31.33-PM-1024x460.png" alt="" width="614" height="276" /></a></p>
<p>The third tap is titled Systems and looks to be the same as where you enter your iOS device IDs. For practice I went ahead and registered my MacBook Air. I didn&#8217;t know that even Macs had hardware device identifiers! You can find the one for your machine on the &#8220;About this Mac&#8221; and then look for &#8220;Hardware UUID&#8221;.</p>
<p>Just like with iOS you are apparently limited to registering 100 such systems per year. Obviously this has to be only for testing purposes, like iCloud and Push Notifications, right?</p>
<p>The fourth and last step is to titled Provisioning Profiles, again a concept we met in the iOS world. Again a big blue button leads to a selection between either Development or Production, where I believe the latter to mean the same as Distribution.</p>
<p>For a Development profile you specify a name or description, choose the previously generated bundle identifier, select the systems that are allowed to run this and the developer certificate. For the Production profile I was presented with two Mac Application Distribution Signing Certificates, so I chose the one with a later expiration date. That must have been one of the two that I saw earlier, but couldn&#8217;t remember creating. Naturally production apps don&#8217;t have any restriction regarding systems, so this is grayed out.</p>
<p>Once the button on the following page turns from Processing to Download you get to see a new pref pane that you never noticed before. Just like on iOS there is also a profiles section in your system settings.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-5.00.02-PM.png"><img class="alignnone size-full wp-image-5639" title="Profile Pref Pane" src="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-5.00.02-PM.png" alt="" width="469" height="341" /></a></p>
<p>One thing that stumped me at first was that I got an error message when I tried the same exercise with the production provisioning profile which happens automatically after download. I suppose that you cannot install a production provisioning profile in your profiles pref pane because it does not have your device identifier. Also on iOS you wouldn&#8217;t ever install the app store distribution profile on a device.</p>
<p>Adding these new provisioning profiles to the Xcode organizer, under devices, worked fine. You can see my automatically managed team provisioning profile for iOS and the two new Mac provisioning profiles. And actually this confirms what I suspected for the production profile: &#8220;This profile cannot be installed on devices&#8221;. Aha. Thanks Apple for letting me think for a few minutes that I did something wrong &#8230;</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-5.05.33-PM.png"><img class="alignnone size-full wp-image-5640" title="Mac provisioning profiles in Xcode organizer" src="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-5.05.33-PM.png" alt="" width="578" height="475" /></a></p>
<p>That seems to be all in terms of general setup, next I did a fresh checkout of the app&#8217;s trunk from my Subversion repository &#8230; and made a fresh cup of tea to calm my nerves, I&#8217;ve started getting sweaty palms from all the excitement.</p>
<h3>Creating a New App on iTunes Connect</h3>
<p>Before getting into the intricacies of building the app I had to do the work required for apps on iTunes Connect to get a new app id number which is needed for the &#8220;Rate this app&#8221; button. This number is assigned by Apple when you create the app on the iTunes Connect portal.</p>
<p>So I logged into the well known <a href="http://itunesconnect.apple.com">http://itunesconnect.apple.com</a>, clicked the &#8220;Add new app&#8221; and chose Mac OS X App.</p>
<p>You choose a name for the app, an SKU code (I usually take the app name in upper case characters) and choose the correct bundle identifier which we created earlier. You are again reminded that <em>&#8220;the Bundle ID cannot be changed if the first version of your app has been approved or if you have enabled Game Center or the iAd Network.&#8221;</em></p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-5.33.47-PM.png"><img class="alignnone size-large wp-image-5642" title="Creating the App on ITC" src="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-5.33.47-PM-1024x656.png" alt="" width="614" height="394" /></a></p>
<p>Next you select the availability date and a pricing tier as you are used to.</p>
<p>On the third screen you have the usual elements to fill out, a description, rating, URLs. Been there, done that.</p>
<p>The first problem I ran into was to provide an acceptable screen shot. Earlier I had simply opened the app and made a screen shot of the app window. Turns out it must be a JPEG, TIF or PNG file that is 1280&#215;800 or 1440&#215;900 pixels, at least 72 DPI and in the RGB color space. A bit of a problem for me on a MacBook Air, since the maximum resolution there is 1366&#215;768.</p>
<p>The trick I used was to switch the display to 1152&#215;720 (stretched), put the app in full screen mode and make a screenshot with Shift+Cmd+3 to not get a shadow. This was easily upscaled to 1280&#215;800 by means of the Preview app. This PNG was accepted without problems.</p>
<p>After a nerve-wrecking long wait on hitting the Submit button, the creation of the app worked and I got my app identifier. I found it odd that there was no means to upload an app icon, but I figure that the icon contained in the app bundle is probably of sufficient resolution for Apple to take it from there.</p>
<h3>Building the Code</h3>
<p>So back to Xcode where I had the app already running in debug so that I could make the screenshot. So first check was for which mode the Archive scheme was set: release. Next I went into the target settings and adjusted code signing to match my production provisioning profile, the &#8220;3rd Party Mac Developer Application&#8221; option.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-6.08.14-PM.png"><img class="alignnone size-full wp-image-5643" title="Setting the Code-Signing Identity" src="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-6.08.14-PM.png" alt="" width="512" height="144" /></a></p>
<p>Building the code for the first time like this triggered lots of warnings that seem to come from using attributes in xib files that are not supported prior to 10.7. I also found a warning about <a href="https://github.com/nickpaulson/NPReceiptVerification">receipt validation</a> (by Nick Paulsen) not being enabled, I had heard about this mechanism that allows Mac apps to validate their honest origin as the MAS.</p>
<p>So I enabled the define after adjusting the bundle identifier (com.drobnik.Linguan) and bundle version (1.0), to see several linker errors. I had to add the IOKit, Security and libcrypto dynamic libraries to fix these.</p>
<p>After that the Archive build went right through and appeared in the Xcode organizer. I tried the Validate button there, but got another annoyingly unhelpful error message.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-6.23.39-PM.png"><img class="alignnone size-full wp-image-5645" title="Error on Validate" src="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-6.23.39-PM.png" alt="" width="594" height="244" /></a></p>
<p>Well, the app version was still in status &#8220;Prepare to update&#8221; and I had to go in and push the &#8220;Ready to Upload Binary&#8221; button. Et voila! No error message any more on hitting Validate, but instead the selection for app and profile.</p>
<p>Next problem: No valid identity found, even though I was certain that I had set up code signing. I mentioned this earlier, I had forgotten to get the Installer certificate set up as well. This last step only works if you have TWO certificates set up for the app store process: Installer and App.</p>
<p>After getting the second certificate set up too, I still could not see it working, but after a restart Xcode picked up the installer certificate and let me upload the app. Hooray!</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-7.44.54-PM.png"><img class="alignnone size-full wp-image-5648" title="Success!" src="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-7.44.54-PM.png" alt="" width="437" height="295" /></a></p>
<p>&#8220;&#8230; submitted to the App Store for further review&#8221; is again another part that we have met before, also called &#8220;the waiting game&#8221;.</p>
<h3>Conclusion</h3>
<p>Submitting apps to the Mac App Store works just like iOS apps with only very minimal differences.</p>
<ul>
<li>You have 2 certificates for app store distribution: Installer and App</li>
<li>You can also have a certificate for development, though the real need for that escapes me</li>
<li>You have to register your development devices and use a development provisioning profile, probably to test things like iCloud</li>
<li>Setup for code signing is the same, though you use a different certificate to sign the app and to sign the installer package that the uploader generates for you.</li>
<li>Screenshot format is different <img src='http://www.cocoanetics.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </li>
<li>You don&#8217;t submit Icon PNGs, those get pulled by iTunes from the app itself</li>
<li>The rest of the submission dialogs is identical</li>
</ul>
<p>I did not go into Entitlements so far, as October 31st was said to be the last day before Apple said that they are going to be enforcing App Sandboxing. That in itself is a whole different world of pain, because of the way this app works with Xcode projects.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-7.56.09-PM.png"><img class="alignnone size-full wp-image-5649" title="Waiting for Review" src="http://www.cocoanetics.com/files/Screen-Shot-2011-10-31-at-7.56.09-PM.png" alt="" width="469" height="255" /></a></p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5635&amp;md5=e3832f61b8f20c505704fc33a237ce59" 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/10/submitting-your-first-mac-app-store-app/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5635&amp;md5=e3832f61b8f20c505704fc33a237ce59" type="text/html" />"
	</item>
		<item>
		<title>Avoiding Image Decompression Sickness</title>
		<link>http://www.cocoanetics.com/2011/10/avoiding-image-decompression-sickness/</link>
		<comments>http://www.cocoanetics.com/2011/10/avoiding-image-decompression-sickness/#comments</comments>
		<pubDate>Sat, 01 Oct 2011 02:27:54 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5497</guid>
		<description><![CDATA[When starting to work on our iCatalog.framework I stumbled upon an annoying problem, the same that you will face if you ever need to work with large images. &#8220;Large&#8221; meaning of a resolution sufficient to cover the entire screen of an iPad or potentially double that (horizontally and vertically) when dealing with Retina Resolution on a future iPad. Imagine you have a UIScrollView that displays UIImageViews for the individual pages of a catalog or magazine style app. As soon as even one pixel of the following page comes on screen you instantiate (or reuse) a UIImageView and pop it into the scroll view&#8217;s content area. That works quite well in Simulator, but when you test this on the device you find that every time you try to page to the next page, there is a noticeable delay. This delay results from the fact that images need to be decompressed from their file incarnation to be rendered on screen. Unfortunately UIImage does this decompression at the very latest possible moment, i.e. when it is to be displayed. Since adding a new view to the view hierarchy has to occur on the main thread, so does the decompression and subsequent rendering of the image on screen. This is where this annoying stutter or pause is stemming from. You can see the same on app store apps where scrolling through something stutters whenever a new image appears on screen. Label Buy an ad here Readability You have basically two main choices for an image format on disk, JPEG and PNG. Apple generally recommends that you use PNGs as graphics for your user interface because when building your app those get optimized by an open source tool named PNGCRUSH. This changes the PNGs such that they can be decompressed and rendered faster on iOS devices by making them easier to digest for the specific hardware. The first iPad magazines, like Wired, were using PNGs as the image format in which they transported the invidiual magazine pages causing one edition of Wired to take upwards of 500 MB. Just because PNGs are automatically optimized for you, that does not mean they are the apex of wisdom for any kind of purpose. That&#8217;s all nice and dandy for images that you can bundle with your app, but what about images that have to be downloaded over the internet? There are distinct advantages and disadvantages to both formats. Let&#8217;s review&#8230; PNGs can have an alpha channel, JPEGs cannot. PNGs have lossless compression, JPEGs allow you to choose a quality of anywhere between 0 and 100%. So if you need the alpha channel &#8211; how transparent each pixel is &#8211; you are stuck with PNG. But if you don&#8217;t need a pixel-perfect rendition of your image then you can go with the perceptually optimized JPEG which basically omits information you don&#8217;t see anyway. For most kinds of images you can go with around 60-70% of quality without any visual artifacts spoiling the visual fidelity. If you have &#8220;sharp pixels&#8221;, like for text you might want to go higher, for photos you can choose a lower setting. Looking at memory used an image takes multiple chunks of it: space on disk or being transferred over the internet uncompressed space, typically width*height*4 Bytes (RGBA) when displayed in a view the view itself also needs space for the layer backing store There&#8217;s an optimization possible for 1) because instead of copying the compressed bits into memory they can also be mapped there. NSData has the ability of pretending that some space on disk is in memory. When it is being access then you actually access the bytes on disk and not in RAM. CGImage is rumored to know by itself which loading strategy is more efficient. UIImage is basically just a wrapper around CGImage. Then there&#8217;s the question of &#8220;How fast can I get these pixels on screen?&#8221;. The answer to this is comprised of 3 main time intervals: time to alloc/init the UIImage with data on disk time to decompress the bits into an uncompressed format time to transfer the uncompressed bits to a CGContext, potentially resizing, blending, anti-aliasing it To be able to give a definitive answer to a scientific question, we need to take measurements. We need to benchmark. Basic Assumptions and Ingredients I made a benchmark app that I ran on several iOS device I had handy. Since I want to also compare crushed versus non-crushed PNGs I needed to start with a couple of source images that Xcode would crush for me. I would have been nice to also dynamically try out different size, but at present I lack a possibility of doing the pngcrush on the device. So I started with 5 resolutions of the same photo of a flower. Of course a true geek would have contrived of multiple [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/10/avoiding-image-decompression-sickness/"></g:plusone></div><p>When starting to work on our <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 an annoying problem, the same that you will face if you ever need to work with large images. &#8220;Large&#8221; meaning of a resolution sufficient to cover the entire screen of an iPad or potentially double that (horizontally and vertically) when dealing with Retina Resolution on a future iPad.</p>
<p>Imagine you have a UIScrollView that displays UIImageViews for the individual pages of a catalog or magazine style app. As soon as even one pixel of the following page comes on screen you instantiate (or reuse) a UIImageView and pop it into the scroll view&#8217;s content area. That works quite well in Simulator, but when you test this on the device you find that every time you try to page to the next page, there is a noticeable delay. This delay results from the fact that images need to be decompressed from their file incarnation to be rendered on screen. Unfortunately UIImage does this decompression at the very latest possible moment, i.e. when it is to be displayed.</p>
<p>Since adding a new view to the view hierarchy has to occur on the main thread, so does the decompression and subsequent rendering of the image on screen. This is where this annoying stutter or pause is stemming from. You can see the same on app store apps where scrolling through something stutters whenever a new image appears on screen.</p>
<p><span id="more-5497"></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>You have basically two main choices for an image format on disk, JPEG and PNG. Apple generally recommends that you use PNGs as graphics for your user interface because when building your app those get optimized by an open source tool named <a href="http://pmt.sourceforge.net/pngcrush/">PNGCRUSH</a>. This changes the PNGs such that they can be decompressed and rendered faster on iOS devices by making them easier to digest for the specific hardware. The first iPad magazines, like Wired, were using PNGs as the image format in which they transported the invidiual magazine pages causing one edition of Wired to take<a title="Saturday Morning, Breakfast, Wired eMag" href="http://www.cocoanetics.com/2010/05/saturday-morning-breakfast-wired-emag/"> upwards of 500 MB</a>.</p>
<p>Just because PNGs are automatically optimized for you, that does not mean they are the apex of wisdom for any kind of purpose. That&#8217;s all nice and dandy for images that you can bundle with your app, but what about images that have to be <strong>downloaded over the internet</strong>? There are distinct advantages and disadvantages to both formats. Let&#8217;s review&#8230;</p>
<p>PNGs can have an alpha channel, JPEGs cannot. PNGs have lossless compression, JPEGs allow you to choose a quality of anywhere between 0 and 100%. So if you need the alpha channel &#8211; how transparent each pixel is &#8211; you are stuck with PNG. But if you don&#8217;t need a pixel-perfect rendition of your image then you can go with the perceptually optimized JPEG which basically omits information you don&#8217;t see anyway. For most kinds of images you can go with around 60-70% of quality without any visual artifacts spoiling the visual fidelity. If you have &#8220;sharp pixels&#8221;, like for text you might want to go higher, for photos you can choose a lower setting.</p>
<p>Looking at memory used an image takes multiple chunks of it:</p>
<ol>
<li>space on disk or being transferred over the internet</li>
<li>uncompressed space, typically width*height*4 Bytes (RGBA)</li>
<li>when displayed in a view the view itself also needs space for the layer backing store</li>
</ol>
<p>There&#8217;s an optimization possible for 1) because instead of copying the compressed bits into memory they can also be mapped there. NSData has the ability of pretending that some space on disk is in memory. When it is being access then you actually access the bytes on disk and not in RAM. CGImage is rumored to know by itself which loading strategy is more efficient. UIImage is basically just a wrapper around CGImage.</p>
<p>Then there&#8217;s the question of &#8220;How fast can I get these pixels on screen?&#8221;. The answer to this is comprised of 3 main time intervals:</p>
<ol>
<li>time to alloc/init the UIImage with data on disk</li>
<li>time to decompress the bits into an uncompressed format</li>
<li>time to transfer the uncompressed bits to a CGContext, potentially resizing, blending, anti-aliasing it</li>
</ol>
<p>To be able to give a definitive answer to a scientific question, we need to take measurements. We need to benchmark.</p>
<p><span class="Apple-style-span" style="font-size: 15px; font-weight: bold;">Basic Assumptions and Ingredients</span></p>
<p>I <a href="https://github.com/Cocoanetics/Cocoanetics-Benchmarks">made a benchmark app</a> that I ran on several iOS device I had handy. Since I want to also compare crushed versus non-crushed PNGs I needed to start with a couple of source images that Xcode would crush for me. I would have been nice to also dynamically try out different size, but at present I lack a possibility of doing the pngcrush on the device. So I started with 5 resolutions of the same photo of a flower. Of course a true geek would have contrived of multiple different images representing both highly compressible, medium and non-compressable source material. But I could not be bothered. And please don&#8217;t get me started on sample size. TOO MUCH INFORMATION.</p>
<p>Please forgive odd outliers and the lack of resolution due to 1 ms being the minimum unit. We are not after a doctorate in image processing, but some practical information.</p>
<p>We are mostly interested in a general comparison of compression schemes and not specific niche cases. The benchmark includes 128*96, 256*192, 512*384, 1024*768 and 2048*1536 resolutions and we clocked Crushed versus Non-Crushed PNG, and JPEGS ranging from 10% to 100% quality in 10% increments. This benchmark was run on iPad 1+2, iPhone 3G, 3GS and 4. This should give us multiple measurements to evaluate performance between formats as well as between devices.</p>
<p><a href="http://www.cocoanetics.com/files/Flower_2048x1536.90.jpg"><img class="alignnone size-medium wp-image-5518" title="Test Image Flower_2048x1536.90" src="http://www.cocoanetics.com/files/Flower_2048x1536.90-300x225.jpg" alt="" width="300" height="225" /></a></p>
<p>First, let&#8217;s look at raw device performance. Hardware descriptions from Wikipedia:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/IPhone_3G#Processor_and_memory">iPhone 3G</a>: &#8220;Most of the iPhone 3G&#8217;s internal hardware were based on the original iPhone. It still included a Samsung 32-bit RISC ARM11 620 MHz processor (underclocked to 412 MHz), a PowerVR MBX Lite 3D GPU, and 128 MB of eDRAM.&#8221;</li>
<li><a href="http://en.wikipedia.org/wiki/IPhone_3GS#Processor_and_memory">iPhone 3GS</a>: &#8220;The iPhone 3GS is powered by the Samsung APL0298C05 chip, which was designed and manufactured by <a title="Samsung" href="http://en.wikipedia.org/wiki/Samsung">Samsung</a>. This system-on-a-chip is composed of an <a title="ARM Cortex-A8" href="http://en.wikipedia.org/wiki/ARM_Cortex-A8">ARM Cortex-A8</a> CPU core underclocked to 600 MHz (from 833 MHz), integrated with a<a title="PowerVR" href="http://en.wikipedia.org/wiki/PowerVR#Series5_.28SGX.29">PowerVR SGX</a> 535 GPU. It also has 256 MB of eDRAM. The additional eDRAM supports increased performance and multi-tasking in iOS 4.&#8221;</li>
<li><a href="http://en.wikipedia.org/wiki/IPhone_4#Processor_and_memory">iPhone 4</a>: &#8220;The iPhone 4 is powered by the <a title="Apple A4" href="http://en.wikipedia.org/wiki/Apple_A4">Apple A4</a> chip, which was designed by <a title="Intrinsity" href="http://en.wikipedia.org/wiki/Intrinsity">Intrinsity</a> and, like all previous iPhone models, manufactured by <a title="Samsung Group" href="http://en.wikipedia.org/wiki/Samsung_Group">Samsung</a>. This <a title="System-on-a-chip" href="http://en.wikipedia.org/wiki/System-on-a-chip">system-on-a-chip</a> is composed of an <a title="ARM architecture" href="http://en.wikipedia.org/wiki/ARM_architecture">ARM Cortex-A8</a> <a title="Central processing unit" href="http://en.wikipedia.org/wiki/Central_processing_unit">CPU</a> integrated with a <a title="PowerVR" href="http://en.wikipedia.org/wiki/PowerVR">PowerVR SGX 535</a> <a title="Graphics processing unit" href="http://en.wikipedia.org/wiki/Graphics_processing_unit">GPU</a>. The Apple A4 is also used in the <a title="IPad" href="http://en.wikipedia.org/wiki/IPad">iPad</a> where it is clocked at its rated speed of 1 <a title="GHz" href="http://en.wikipedia.org/wiki/GHz">GHz</a>. The clock speed in the iPhone 4 has not been disclosed. All previous <a title="List of iOS devices" href="http://en.wikipedia.org/wiki/List_of_iOS_devices#iPhone">models</a> of the iPhone have <a title="Underclock" href="http://en.wikipedia.org/wiki/Underclock">underclocked</a> the CPU, which typically extends battery life and lowers <a title="CPU power dissipation" href="http://en.wikipedia.org/wiki/CPU_power_dissipation">heat dissipation</a>.&#8221;</li>
<li><a href="http://en.wikipedia.org/wiki/Ipad#Technical_specifications">iPad</a>: 1 GHz <a href="http://en.wikipedia.org/wiki/Apple_A4">Apple A4</a> system-on-a-chip with 256 GB DDR RAM in chip package</li>
<li><a href="http://en.wikipedia.org/wiki/Ipad#Technical_specifications">iPad 2</a>: 1 GHz (dynamically clocked) dual-core <a href="http://en.wikipedia.org/wiki/Apple_A5">Apple A5</a> system on a chip with 512 GB DDR2 RAM in chip package</li>
</ul>
<p>Two of these devices have the same processor, the iPad 1 and iPhone 4. We see the <strong>major shift in performance</strong> at the same time when Apple moved to their own silicone. The (under clocked) A4 is still twice as fast as the ARM Cortext-A8 and PowerVR SGC 535 GPU.</p>
<h3>Crushed by the Evidence</h3>
<p>Total time for loading, decompressing and rendering  a 90% JPEG at 1024*768:</p>
<ul>
<li><strong>iPhone 3G:</strong> 527 ms</li>
<li><strong>iPhone 3GS:</strong> 134 ms</li>
<li><strong>iPad:</strong> 79 ms</li>
<li><strong>iPhone 4:</strong> 70 ms</li>
<li><strong>iPad 2:</strong> 51 ms</li>
</ul>
<p>Comparing Crushed versus Non-Crushed PNG, also 1024*768:</p>
<ul>
<li><strong>iPhone 3G:</strong> 866 ms &#8211; 1032 ms = 16% faster</li>
<li><strong>iPhone 3GS:</strong> 249 ms &#8211; 458 ms = 46% faster</li>
<li><strong>iPad:</strong> 130 ms &#8211; 256 ms = 49% faster</li>
<li><strong>iPhone 4: </strong>179 ms &#8211; 309 ms = 42% faster</li>
<li><strong>iPad 2:</strong> 105 ms &#8211; 208 ms = 49% faster</li>
</ul>
<p>On iPhone 3GS and above it is a good rule of thumb to say that crushed<em> PNGs are twice as fast as uncrushed</em> ones.</p>
<p>Following are the charts for all 5 test resolutions. I have plotted alloc/init, decompress and drawing time needed separately. The bars are ordered front to back by speed, smaller bars mean faster. Charts courtesy of <a href="http://www.cocoapedia.org/wiki/Christian_Pfandler">Christian Pfandler</a>.</p>
<p>At first glance you can see that the relationship between compression schemes is more or less the same within one chart i.e. one resolution. But I still present all to you here for sake of completeness.</p>
<p><a href="http://www.cocoanetics.com/files/Chart_0128.png"><img class="alignnone size-full wp-image-5512" title="Chart 128" src="http://www.cocoanetics.com/files/Chart_0128.png" alt="" width="644" height="511" /></a></p>
<p><a href="http://www.cocoanetics.com/files/Chart_0256.png"><img class="alignnone size-full wp-image-5513" title="Chart 256" src="http://www.cocoanetics.com/files/Chart_0256.png" alt="" width="644" height="511" /></a></p>
<p>&nbsp;</p>
<p>The first two charts represent resolutions that you would encounter when making images to supplement your user interface. Ignoring the fact that old hardware is slow you can draw a mental line at around 20 ms. This is the limit whereabouts the images are small enough to be drawn directly in a timely manner. Anything about this line means you either have a crappy old iPhone or you have to get the decompression off the main thread if you don&#8217;t want your app to be all stuttery.</p>
<p>The next three charts are of resolutions that &#8211; for the sake of analysis &#8211; we can deem as representative of phone full screen, pad full screen and page retina full screen.</p>
<p><a href="http://www.cocoanetics.com/files/Chart_0512.png"><img class="alignnone size-full wp-image-5514" title="Chart 512" src="http://www.cocoanetics.com/files/Chart_0512.png" alt="" width="644" height="511" /></a></p>
<p>&nbsp;</p>
<p>Up to this point you might still survive with lots of UIImages and UIImageViews especially if you don&#8217;t care about fluidity on older devices. Though you see that you take a severe performance hit by using PNGs at this stage. At full screen phone resolution you definitely want to prefer JPEG.</p>
<p><a href="http://www.cocoanetics.com/files/Chart_1024.png"><img class="alignnone size-full wp-image-5515" title="Chart 1024" src="http://www.cocoanetics.com/files/Chart_1024.png" alt="" width="644" height="511" /></a></p>
<p>&nbsp;</p>
<p>At these resolutions we are way beyond the comfort zone. Even the fastest device can only decompress between 2 (iPad Retina) and 10 (iPad full screen) huge images per second.</p>
<p>Even if you get the decompressing off the main thread the drawing itself still takes some significant time. You want to have this done with CATiledLayer, split your images into tiles and cache the hell out of it.</p>
<p><a href="http://www.cocoanetics.com/files/Chart_2048.png"><img class="alignnone size-full wp-image-5516" title="Chart 2048" src="http://www.cocoanetics.com/files/Chart_2048.png" alt="" width="644" height="511" /></a></p>
<p>&nbsp;</p>
<p>Uniformly we can see that the red portion (decompress) is always the part that takes the most time. Drawing time is only dependent on the resolution, not the complexity of the compression scheme, which makes sense because at that point the game is won by points &#8230; pixels that is.</p>
<p>Generally a 100% JPEG is about equivalent to a crushed PNG. I can think of two reasons why you would choose that: a) you cannot dynamically create a crushed PNG on an iOS device, b) file size does not matter and you want to make sure you store a pixel-perfect replica.</p>
<p>Parallel to the file sizes (see below) you see how processing time increases linear from JPG 10% to JPG 90% and goes upwards steeply from there.</p>
<p>An interesting observation is buried in the last chart. In order for responsiveness to be on an iPad Retina display as we are used to with iPad 1+2 the image decoding would need to be 3-4 times faster than the iPad 2. From iPad 1 to 2 it only doubled. There you have the reason why iPad 2 cannot drive Retina just yet. It might not even be the next generation hardware, but 2 generations in the future that will be the first to manage that.</p>
<h3>File Sizes</h3>
<h3><span class="Apple-style-span" style="font-size: 13px; font-weight: normal;">Let&#8217;s review the file sizes. Crushing PNGs makes them faster to render, but does it decrease file size?</span></h3>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-09-30-at-5.08.04-PM.png"><img class="alignnone size-full wp-image-5498" title="File Sizes" src="http://www.cocoanetics.com/files/Screen-Shot-2011-09-30-at-5.08.04-PM.png" alt="" width="608" height="403" /></a><br />
Crushing PNGs reduces file size only for large images by a minimal amount. The maximum quality of JPEG somewhat compares to crushed PNGs, but setting it to 100% defeats the purpose of compression. You can see that choosing 90% instead of 100% more than halves the file size for any resolution. JPEG file size increases linear with quality but increases sharply over 90%.</p>
<h3>Real Time?</h3>
<p>When looking at the numbers for full screen images you see a problem that we&#8217;ve been having ever since Apple introduced the tablet form factor. A 70% JPEG at full screen resolution takes a whopping 75 ms to display on an iPad 1, 49 ms on an iPad 2 nowhere near real time. Meaning that this is way slower than the 60 fps you should be aiming for wherever possible. 13 fps or 20 fps are well below the human threshold of 30 frames per second that you need to consider a movement smooth. It turns my stomach seeing smooth scrolling and when a new image enters the POV the scroll motion gets stuck for a 20th of a second and then have it jump to again match your finger.</p>
<p>If we could take the decompression out of the equation then the numbers would look far more promising: 17 &#8211; 18 ms just for the drawing equate to about 55 fps, smooth as butter. Interestingly the iPads are not so much different in just blasting pixels onto layers, it&#8217;s the hardware accelerated decompression that makes the big difference.</p>
<p>One easy way around this was for me to simply draw the catalog pages in iCatalog on a CATiledLayer with fading disabled. This would cause the image display to occur on the background thread used for the tiling with no impact on the scrolling performance. The only thing you might notice there is that if you scroll quickly to the right pages might pop into sight after a brief delay. One disadvantage of this approach is that it is hard to get transitions between portrait and landscape orientations to look nice.</p>
<p>The other &#8211; albeit more advanced method &#8211; would be to force decompression on images just in time before they are needed.</p>
<h3>Forceful Decompression</h3>
<p>The first time you need an image&#8217;s pixels iOS is decompressing it. Usually this decompressed version sticks around &#8211; RAM permitting. So it makes very little sense to decompress an image by means of rendering it into a new one. This only has you end up with TWO uncompressed images, at least for a short time. It is sufficient to &#8220;just pretend&#8221;:</p>

<div class="wp_codebox"><table><tr id="p549777"><td class="code" id="p5497code77"><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>decompressImage<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIImage <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
	UIGraphicsBeginImageContext<span style="color: #002200;">&#40;</span>CGSizeMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">1</span>, <span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#91;</span>image drawAtPoint<span style="color: #002200;">:</span>CGPointZero<span style="color: #002200;">&#93;</span>;
	UIGraphicsEndImageContext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This causes the image to decompress, even though the image context is just 1 pixel large.</p>
<p>Strangely I could not consistently get the UIImage to keep the decompressed version around if it was just initWithContentsOfFile. Instead I had to use the ImageIO framework (available as of iOS 4) which provides an option to explicitly specify that you want to keep the decompressed version:</p>

<div class="wp_codebox"><table><tr id="p549778"><td class="code" id="p5497code78"><pre class="objc" style="font-family:monospace;"><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>dict <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: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/"><span style="color: #400080;">NSNumber</span></a> numberWithBool<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>
                      forKey<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>kCGImageSourceShouldCache<span style="color: #002200;">&#93;</span>;
&nbsp;
CGImageSourceRef source <span style="color: #002200;">=</span> CGImageSourceCreateWithURL<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>CFURLRef<span style="color: #002200;">&#41;</span>url, <span style="color: #a61390;">NULL</span><span style="color: #002200;">&#41;</span>;
CGImageRef cgImage <span style="color: #002200;">=</span> CGImageSourceCreateImageAtIndex<span style="color: #002200;">&#40;</span>source, <span style="color: #2400d9;">0</span>, <span style="color: #002200;">&#40;</span>CFDictionaryRef<span style="color: #002200;">&#41;</span>dict<span style="color: #002200;">&#41;</span>;
&nbsp;
UIImage <span style="color: #002200;">*</span>retImage <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIImage imageWithCGImage<span style="color: #002200;">:</span>cgImage<span style="color: #002200;">&#93;</span>;
CGImageRelease<span style="color: #002200;">&#40;</span>cgImage<span style="color: #002200;">&#41;</span>;
CFRelease<span style="color: #002200;">&#40;</span>source<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>Initializing the images like this I could see the times drop to indicate that decompression would only take place once. The first call to decompress took long time, the second no time at all. The magic code word is kCGImageSourceShouldCache which you can specify either for the CGImageSource or the CGImageSourceCreateImageAtIndex, according to the header this means:</p>
<blockquote><p>Specifies whether the image should be cached in a decoded form. The value of this key must be a CFBooleanRef; the default value is kCFBooleanFalse.</p></blockquote>
<p>If I set it to NO then I could see the drawing time also grow by the decoding time. If I set it to YES the decoding would only be happening once.</p>
<h3>Conclusion</h3>
<p>If you absolutely need an alpha channel or have to go with PNGs then it is advisable to install the pngcrush tool on your web server and have it process all your PNGs. In almost all other cases high quality JPEGs combine smaller file sizes (i.e. faster transmission) with faster compression and rendering.</p>
<p>It turns out that PNGs are great for small images that you would use for UI elements, but they are not reasonable to use for any full screen applications like catalogues or magazines. There you would want to choose a compression quality between 60 and 80% depending on your source material.</p>
<p>In terms of getting it all to display you will want to hang onto UIImage instances from which you have drawn once because those have a cached uncompressed version of the file in them. And where you don&#8217;t the visual pause for a large image to appear on screen you will have to force decompression for a couple of images in advance. But bear in mind that these will take large amounts of RAM and if you are overdoing it that might cause your app to be terminated. NSCache is a great place to place frequently used images because this automatically takes care of evicting the images when RAM becomes scarce.</p>
<p>It is unfortunate that we don&#8217;t have any way to know whether or not an image still needs decompressing or not. Also an image might have evicted the uncompressed version without informing us as to this effect. That might be a good Radar to raise at Apple&#8217;s bug reporting site. But fortunately accessing the image as shown above takes no time if the image is already decompressed. So you could just do that not only &#8220;just in time&#8221; but also &#8220;just in case&#8221;.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5497&amp;md5=4da68a7e73c6cb86f789001d22f14db1" 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/10/avoiding-image-decompression-sickness/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5497&amp;md5=4da68a7e73c6cb86f789001d22f14db1" type="text/html" />"
	</item>
		<item>
		<title>Taming HTML Parsing with libxml (1)</title>
		<link>http://www.cocoanetics.com/2011/09/taming-html-parsing-with-libxml-1/</link>
		<comments>http://www.cocoanetics.com/2011/09/taming-html-parsing-with-libxml-1/#comments</comments>
		<pubDate>Sun, 18 Sep 2011 08:27:57 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5441</guid>
		<description><![CDATA[For the NSAttributedString+HTML Open Source project I chose to implement parsing of HTML with a set of NSScanner category methods. The resulting code is relatively easy to understand but has a couple of annoying drawbacks. You have to duplicate the NSData and convert it into an NSString effectively doubling the amount of memory needed. Then while parsing I am building an adhoc tree of DTHTMLElement instances adding yet another copy of the document in RAM. When parsing HTML &#8211; and by extension XML &#8211; you have two kinds of operating mode available: you can have the Sequential Access Method (SAX) where walking through the document triggers events on the individual pieces of it. The second method is to build a tree of nodes, a Document Object Model (DOM). NSScanner lends itself to SAX, but in this case it is less than ideal because for CSS inheritance some sort of hierarchy is necessary to walk up on. In this post we will begin to explore the industry-standard libxml library and see how we can thinly wrap it in Objective-C that it plays nicely with our code. Label Buy an ad here Readability Getting libxml into your Xcode project is straightforward. Fortunately for us libxml is so old and established that you can find it already installed on Unix, Mac and iOS platforms. There are two kinds of libraries in C: static and dynamic. libxml is the latter which you can recognize by the .dylib extension. Adding the Library First we need to add the library providing all the XML and HTML structures and functions. We are actually using version 2.2 of libxml, the file libxml2.dylib is a symbolic link to libxml2.2.dylib. Next &#8211; because libxml is not a framework that would package the necessary headers with it &#8211; we also need to tell Xcode where the headers can be found. Since libxml also comes with OSX, its headers &#8211; just like all other OSX system libraries can be found in /usr/include. Add /usr/include/libxml2  to the Header Search Paths and we&#8217;re set. Now all we need to do to access libxml&#8217;s parsing methods and data structures is to add the appropriate import. Most of the internal structures are shared between the XML and HTML parsers and so we just need the HTMLparser header. #import &#60;libxml/HTMLparser.h&#62; Document Structure Before we get into parsing let me show you how libxml represents HTML documents. Everything in libxml is a node. Because C does not have a concept of objects the classical method of representing a tree is by having C structs that have member variables pointing to other structs. A child is just a pointer to the child struct/node. If there can be more than one item, i.e. a list, this is represented by a linked list where the first node points to the next and so on until the very last node has a NULL pointer. The smallest unit in libxml is xmlNode structure which is defined as such: /** * xmlNode: * * A node in an XML tree. */ typedef struct _xmlNode xmlNode; typedef xmlNode *xmlNodePtr; struct _xmlNode &#123; void *_private; /* application data */ xmlElementType type; /* type number, must be second ! */ const xmlChar *name; /* the name of the node, or the entity */ struct _xmlNode *children; /* parent-&#62;childs link */ struct _xmlNode *last; /* last child link */ struct _xmlNode *parent; /* child-&#62;parent link */ struct _xmlNode *next; /* next sibling link */ struct _xmlNode *prev; /* previous sibling link */ struct _xmlDoc *doc; /* the containing document */ &#160; /* End of common part */ xmlNs *ns; /* pointer to the associated namespace */ xmlChar *content; /* the content */ struct _xmlAttr *properties;/* properties list */ xmlNs *nsDef; /* namespace definitions on this node */ void *psvi; /* for type/PSVI informations */ unsigned short line; /* line number */ unsigned short extra; /* extra data for XPath/XSLT */ &#125;; The useful links depicted in the above chart as children, last, parent, next, prev and doc. The type value is the kind of role this node plays. If it is a tag then it is an XML_ELEMENT_NODE. The contents of a tag is represented by an XML_TEXT_NODE. Attributes are XML_ATTRIBUTE_NODE. Note that even if the original HTML does not contain a DTD, html or body tag these will be implied by the parser. Let&#8217;s Parse Already I sense that you grow impatient with me. Ok ok, we&#8217;re getting right to it now that you understand how libxml represents DOMs. Assume we have some HTML data downloaded from the web, the NSURL of it is in _baseURL. // NSData data contains the document data // encoding is the NSStringEncoding of the data // baseURL the documents base URL, i.e. location &#160; CFStringEncoding cfenc = CFStringConvertNSStringEncodingToEncoding&#40;encoding&#41;; CFStringRef cfencstr = [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/09/taming-html-parsing-with-libxml-1/"></g:plusone></div><p>For the NSAttributedString+HTML Open Source project I chose to implement parsing of HTML with a set of NSScanner category methods. The resulting code is relatively easy to understand but has a couple of annoying drawbacks. You have to duplicate the NSData and convert it into an NSString effectively doubling the amount of memory needed. Then while parsing I am building an adhoc tree of DTHTMLElement instances adding yet another copy of the document in RAM.</p>
<p>When parsing HTML &#8211; and by extension XML &#8211; you have two kinds of operating mode available: you can have the Sequential Access Method (SAX) where walking through the document triggers events on the individual pieces of it. The second method is to build a tree of nodes, a Document Object Model (DOM). NSScanner lends itself to SAX, but in this case it is less than ideal because for CSS inheritance some sort of hierarchy is necessary to walk up on.</p>
<p>In this post we will begin to explore the industry-standard libxml library and see how we can thinly wrap it in Objective-C that it plays nicely with our code.</p>
<p><span id="more-5441"></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>Getting libxml into your Xcode project is straightforward. Fortunately for us libxml is so old and established that you can find it already installed on Unix, Mac and iOS platforms. There are two kinds of libraries in C: static and dynamic. libxml is the latter which you can recognize by the .dylib extension.</p>
<h3>Adding the Library</h3>
<p>First we need to add the library providing all the XML and HTML structures and functions. We are actually using version 2.2 of libxml, the file libxml2.dylib is a symbolic link to libxml2.2.dylib.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-09-10-at-8.35.36-PM.png"><img src="http://www.cocoanetics.com/files/Screen-Shot-2011-09-10-at-8.35.36-PM.png" alt="" title="Adding the library" width="385" height="194" class="alignnone size-full wp-image-5442" /></a></p>
<p>Next &#8211; because libxml is not a framework that would package the necessary headers with it &#8211; we also need to tell Xcode where the headers can be found. Since libxml also comes with OSX, its headers &#8211; just like all other OSX system libraries can be found in /usr/include. Add /usr/include/libxml2  to the Header Search Paths and we&#8217;re set.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-09-10-at-8.38.35-PM.png"><img class="alignnone size-full wp-image-5443" title="Setting the Header Search Path" src="http://www.cocoanetics.com/files/Screen-Shot-2011-09-10-at-8.38.35-PM.png" alt="" width="598" height="207" /></a></p>
<p>Now all we need to do to access libxml&#8217;s parsing methods and data structures is to add the appropriate import. Most of the internal structures are shared between the XML and HTML parsers and so we just need the HTMLparser header.</p>

<div class="wp_codebox"><table><tr id="p544184"><td class="code" id="p5441code84"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &lt;libxml/HTMLparser.h&gt;</span></pre></td></tr></table></div>

<h2>Document Structure</h2>
<p>Before we get into parsing let me show you how libxml represents HTML documents. Everything in libxml is a node. Because C does not have a concept of objects the classical method of representing a tree is by having C structs that have member variables pointing to other structs. A child is just a pointer to the child struct/node. If there can be more than one item, i.e. a list, this is represented by a linked list where the first node points to the next and so on until the very last node has a NULL pointer.</p>
<p><a href="http://www.cocoanetics.com/files/libxml1.png"><img src="http://www.cocoanetics.com/files/libxml1.png" alt="" title="libxml Node Structure" width="517" height="636" class="alignnone size-full wp-image-5454" /></a></p>
<p>The smallest unit in libxml is xmlNode structure which is defined as such:</p>

<div class="wp_codebox"><table><tr id="p544185"><td class="code" id="p5441code85"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/**
 * xmlNode:
 *
 * A node in an XML tree.
 */</span>
<span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> _xmlNode xmlNode<span style="color: #339933;">;</span>
<span style="color: #993333;">typedef</span> xmlNode <span style="color: #339933;">*</span>xmlNodePtr<span style="color: #339933;">;</span>
<span style="color: #993333;">struct</span> _xmlNode <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">void</span>           <span style="color: #339933;">*</span>_private<span style="color: #339933;">;</span>	<span style="color: #808080; font-style: italic;">/* application data */</span>
    xmlElementType   type<span style="color: #339933;">;</span>	<span style="color: #808080; font-style: italic;">/* type number, must be second ! */</span>
    <span style="color: #993333;">const</span> xmlChar   <span style="color: #339933;">*</span>name<span style="color: #339933;">;</span>      <span style="color: #808080; font-style: italic;">/* the name of the node, or the entity */</span>
    <span style="color: #993333;">struct</span> _xmlNode <span style="color: #339933;">*</span>children<span style="color: #339933;">;</span>	<span style="color: #808080; font-style: italic;">/* parent-&gt;childs link */</span>
    <span style="color: #993333;">struct</span> _xmlNode <span style="color: #339933;">*</span>last<span style="color: #339933;">;</span>	<span style="color: #808080; font-style: italic;">/* last child link */</span>
    <span style="color: #993333;">struct</span> _xmlNode <span style="color: #339933;">*</span>parent<span style="color: #339933;">;</span>	<span style="color: #808080; font-style: italic;">/* child-&gt;parent link */</span>
    <span style="color: #993333;">struct</span> _xmlNode <span style="color: #339933;">*</span>next<span style="color: #339933;">;</span>	<span style="color: #808080; font-style: italic;">/* next sibling link  */</span>
    <span style="color: #993333;">struct</span> _xmlNode <span style="color: #339933;">*</span>prev<span style="color: #339933;">;</span>	<span style="color: #808080; font-style: italic;">/* previous sibling link  */</span>
    <span style="color: #993333;">struct</span> _xmlDoc  <span style="color: #339933;">*</span>doc<span style="color: #339933;">;</span>	<span style="color: #808080; font-style: italic;">/* the containing document */</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">/* End of common part */</span>
    xmlNs           <span style="color: #339933;">*</span>ns<span style="color: #339933;">;</span>        <span style="color: #808080; font-style: italic;">/* pointer to the associated namespace */</span>
    xmlChar         <span style="color: #339933;">*</span>content<span style="color: #339933;">;</span>   <span style="color: #808080; font-style: italic;">/* the content */</span>
    <span style="color: #993333;">struct</span> _xmlAttr <span style="color: #339933;">*</span>properties<span style="color: #339933;">;</span><span style="color: #808080; font-style: italic;">/* properties list */</span>
    xmlNs           <span style="color: #339933;">*</span>nsDef<span style="color: #339933;">;</span>     <span style="color: #808080; font-style: italic;">/* namespace definitions on this node */</span>
    <span style="color: #993333;">void</span>            <span style="color: #339933;">*</span>psvi<span style="color: #339933;">;</span>	<span style="color: #808080; font-style: italic;">/* for type/PSVI informations */</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">short</span>   line<span style="color: #339933;">;</span>	<span style="color: #808080; font-style: italic;">/* line number */</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">short</span>   extra<span style="color: #339933;">;</span>	<span style="color: #808080; font-style: italic;">/* extra data for XPath/XSLT */</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The useful links depicted in the above chart as children, last, parent, next, prev and doc. The type value is the kind of role this node plays. If it is a tag then it is an XML_ELEMENT_NODE. The contents of a tag is represented by an XML_TEXT_NODE. Attributes are XML_ATTRIBUTE_NODE. Note that even if the original HTML does not contain a DTD, html or body tag these will be implied by the parser.</p>
<h2>Let&#8217;s Parse Already</h2>
<p>I sense that you grow impatient with me. Ok ok, we&#8217;re getting right to it now that you understand how libxml represents DOMs. Assume we have some HTML data downloaded from the web, the NSURL of it is in _baseURL.</p>

<div class="wp_codebox"><table><tr id="p544186"><td class="code" id="p5441code86"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// NSData data contains the document data</span>
<span style="color: #11740a; font-style: italic;">// encoding is the NSStringEncoding of the data</span>
<span style="color: #11740a; font-style: italic;">// baseURL the documents base URL, i.e. location </span>
&nbsp;
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;
htmlDocPtr _htmlDocument <span style="color: #002200;">=</span> htmlReadDoc<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>data bytes<span style="color: #002200;">&#93;</span>,
      <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>baseURL absoluteString<span style="color: #002200;">&#93;</span> UTF8String<span style="color: #002200;">&#93;</span>,
      enc,
      XML_PARSE_NOERROR | XML_PARSE_NOWARNING<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>Since we don&#8217;t need any warnings or errors we can just ignore them by passing some options. The baseURL might be necessary to decode relative URLs contained in the document. And most importantly we cannot assume that UTF8 is used for encoding the bytes so we get the appropriate character set to pass to the parser.</p>
<p>Remember, this is pure C, so once we don&#8217;t need this DOM any more we need to trigger a routine that walks through this linked structures and frees up the reserved memory.</p>

<div class="wp_codebox"><table><tr id="p544187"><td class="code" id="p5441code87"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>_htmlDocument<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
   xmlFreeDoc<span style="color: #002200;">&#40;</span>_htmlDocument<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>If _htmlDocument is not NULL then we have successfully parsed the document. There are multiple methods how we could now use this, but for the final example in this post let me show you a function that just dumps the individual elements to to the log. This demonstrates how to follow the links and also how to access the contents of text elements.</p>

<div class="wp_codebox"><table><tr id="p544188"><td class="code" id="p5441code88"><pre class="objc" style="font-family:monospace;">xmlNodePtr currentNode <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>xmlNodePtr<span style="color: #002200;">&#41;</span>_htmlDocument;
&nbsp;
<span style="color: #a61390;">BOOL</span> beginOfNode <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
&nbsp;
<span style="color: #a61390;">while</span> <span style="color: #002200;">&#40;</span>currentNode<span style="color: #002200;">&#41;</span> 
<span style="color: #002200;">&#123;</span>
    <span style="color: #11740a; font-style: italic;">// output node if it is an element</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>beginOfNode<span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>currentNode<span style="color: #002200;">-</span>&gt;type <span style="color: #002200;">==</span> XML_ELEMENT_NODE<span style="color: #002200;">&#41;</span>
        <span style="color: #002200;">&#123;</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>attrArray <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>xmlAttrPtr attrNode <span style="color: #002200;">=</span> currentNode<span style="color: #002200;">-</span>&gt;properties; 
                 attrNode; attrNode <span style="color: #002200;">=</span> attrNode<span style="color: #002200;">-</span>&gt;next<span style="color: #002200;">&#41;</span>
            <span style="color: #002200;">&#123;</span>
                xmlNodePtr contents <span style="color: #002200;">=</span> attrNode<span style="color: #002200;">-</span>&gt;children;
&nbsp;
                <span style="color: #002200;">&#91;</span>attrArray addObject<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;%s='%s'&quot;</span>, 
                                      attrNode<span style="color: #002200;">-</span>&gt;name, contents<span style="color: #002200;">-</span>&gt;content<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
            <span style="color: #002200;">&#125;</span>
&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>attrString <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>attrArray componentsJoinedByString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot; &quot;</span><span style="color: #002200;">&#93;</span>; 
&nbsp;
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>attrString length<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
            <span style="color: #002200;">&#123;</span>
                attrString <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot; &quot;</span> stringByAppendingString<span style="color: #002200;">:</span>attrString<span style="color: #002200;">&#93;</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;&lt;%s%@&gt;&quot;</span>, currentNode<span style="color: #002200;">-</span>&gt;name, attrString<span style="color: #002200;">&#41;</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>currentNode<span style="color: #002200;">-</span>&gt;type <span style="color: #002200;">==</span> XML_TEXT_NODE<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;%s&quot;</span>, currentNode<span style="color: #002200;">-</span>&gt;content<span style="color: #002200;">&#41;</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>currentNode<span style="color: #002200;">-</span>&gt;type <span style="color: #002200;">==</span> XML_COMMENT_NODE<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;/* %s */&quot;</span>, currentNode<span style="color: #002200;">-</span>&gt;name<span style="color: #002200;">&#41;</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>beginOfNode <span style="color: #002200;">&amp;&amp;</span> currentNode<span style="color: #002200;">-</span>&gt;children<span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        currentNode <span style="color: #002200;">=</span> currentNode<span style="color: #002200;">-</span>&gt;children;
        beginOfNode <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>beginOfNode <span style="color: #002200;">&amp;&amp;</span> currentNode<span style="color: #002200;">-</span>&gt;next<span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        currentNode <span style="color: #002200;">=</span> currentNode<span style="color: #002200;">-</span>&gt;next;
        beginOfNode <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: #002200;">&#123;</span>
        currentNode <span style="color: #002200;">=</span> currentNode<span style="color: #002200;">-</span>&gt;parent;
        beginOfNode <span style="color: #002200;">=</span> <span style="color: #a61390;">NO</span>; <span style="color: #11740a; font-style: italic;">// avoid going to siblings or children</span>
&nbsp;
        <span style="color: #11740a; font-style: italic;">// close node</span>
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>currentNode <span style="color: #002200;">&amp;&amp;</span> currentNode<span style="color: #002200;">-</span>&gt;type <span style="color: #002200;">==</span> XML_ELEMENT_NODE<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;&lt;/%s&gt;&quot;</span>, currentNode<span style="color: #002200;">-</span>&gt;name<span style="color: #002200;">&#41;</span>;
        <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Note how I use %s so that I can use the zero-terminated C strings without having to convert them to NSStrings.</p>
<p>Obviously there are other ways to iterate through the document, for example by means of recursion. But this is meant to show how you can walk through nodes and their children and how you can also get the attributes.</p>
<p>Next time we will have a look how we can somehow wrap this pure C-code that we can more easily find and access parts of it. We cannot simply wrap xmlNode into an Objective-C class because then we might end up freeing the structure while an node instance is still present, thus creating a whole lot of junk pointers and introducing crash potential.</p>
<p>This is the case with the <a href="https://github.com/zootreeves/Objective-C-HMTL-Parser">Objective-C HTML Parser</a> project on GitHub by Ben Reeves. But even though I don&#8217;t share Ben&#8217;s philosophy, his prior work served as the starting point for this article.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5441&amp;md5=359aca393fb40b7c9565559c8d3dda09" 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/09/taming-html-parsing-with-libxml-1/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5441&amp;md5=359aca393fb40b7c9565559c8d3dda09" type="text/html" />"
	</item>
		<item>
		<title>Calculating Area Covered by Keyboard</title>
		<link>http://www.cocoanetics.com/2011/07/calculating-area-covered-by-keyboard/</link>
		<comments>http://www.cocoanetics.com/2011/07/calculating-area-covered-by-keyboard/#comments</comments>
		<pubDate>Sat, 09 Jul 2011 15:11:43 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5249</guid>
		<description><![CDATA[If you show something that contains scrollable content, i.e. UITableView, UIScrollView etc. then you want to make an adjustment when the keyboard shows so that the user can still scroll to the entire content. He wouldn&#8217;t be able to do so if you didn&#8217;t do anything. I&#8217;ve seen several approaches to this so far, but they often hard code a certain position of the view or sizes. Like assuming that the covered view always reaches towards the bottom of the screen or always has a certain amount of space taken away from it by the status bar, navigation bar and possibly toolbar. The whole thing gets even more complicated by the fact the the coordinate system of the app&#8217;s window is always in portrait even though your app rotates. So is the frame of the keyboard which you can get from an info dictionary in several notifications. I&#8217;ll show you the most universally working method I was able to come up with. Label Buy an ad here Readability The first part is obvious, you want to subscribe to two notifications, one for when the keyboard has fully animated in and one for when the keyboard will go away. I&#8217;ve seen people mess with the frame of the covered view, but I generally found this to be disturbing the contents, in the least causing an unnecessary redraw because of the bounds change. Instead I prefer to set the content inset of the scroll view. This does not affect the contents, but permits for additional scroll distance so that the content at the bottom edge can be scrolled into the visible area above the keyboard. The inset for the scroll indicator is separate but needs the same treatment. Note that all this is best done in your UIScrollView subclass. NSNotificationCenter *center = &#91;NSNotificationCenter defaultCenter&#93;; &#91;center addObserver:self selector:@selector&#40;keyboardDidShow:&#41; name:UIKeyboardDidShowNotification object:nil&#93;; &#91;center addObserver:self selector:@selector&#40;keyboardWillHide:&#41; name:UIKeyboardWillHideNotification object:nil&#93;; And of course we remove the observer in the dealloc. - &#40;void&#41;dealloc &#123; &#91;&#91;NSNotificationCenter defaultCenter&#93; removeObserver:self&#93;; &#91;super dealloc&#93;; &#125; When the keyboard is hidden we don&#8217;t want any insets, so we reset them to zero. - &#40;void&#41;keyboardWillHide:&#40;NSNotification *&#41;notification &#123; self.contentInset = UIEdgeInsetsMake&#40;0, 0, 0, 0&#41;; self.scrollIndicatorInsets = self.contentInset; &#125; And now the good part, calculating the correct covered area of the view, regardless of where it is positioned on screen. Yet another complication derives from the fact that if we use the scrollview&#8217;s coordinate system then we get different results depending on the content size. So instead we need to use the superview&#8217;s coordinate system for transforming to and from the window coordinate system. This is necessary because the keyboard is mounted on the window and thus also has window coordinates. - &#40;void&#41;keyboardDidShow:&#40;NSNotification *&#41;notification &#123; // keyboard frame is in window coordinates NSDictionary *userInfo = &#91;notification userInfo&#93;; CGRect keyboardFrame = &#91;&#91;userInfo objectForKey:UIKeyboardFrameEndUserInfoKey&#93; CGRectValue&#93;; &#160; // convert own frame to window coordinates, frame is in superview's coordinates CGRect ownFrame = &#91;self.window convertRect:self.frame fromView:self.superview&#93;; &#160; // calculate the area of own frame that is covered by keyboard CGRect coveredFrame = CGRectIntersection&#40;ownFrame, keyboardFrame&#41;; &#160; // now this might be rotated, so convert it back coveredFrame = &#91;self.window convertRect:coveredFrame toView:self.superview&#93;; &#160; // set inset to make up for covered array at bottom self.contentInset = UIEdgeInsetsMake&#40;0, 0, coveredFrame.size.height, 0&#41;; self.scrollIndicatorInsets = self.contentInset; &#125; We use the handy CGRectIntersection function to get a rectangle that is common to both the keyboard and view frame. Since there might have been a rotation transform somewhere in between, we also need to convert back to our original superview&#8217;s coordinate system. And that&#8217;s it, now coveredFrame gives us exactly the area of our view that is covered and thus the hight is also the bottom inset we need to apply.]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/07/calculating-area-covered-by-keyboard/"></g:plusone></div><p>If you show something that contains scrollable content, i.e. UITableView, UIScrollView etc. then you want to make an adjustment when the keyboard shows so that the user can still scroll to the entire content. He wouldn&#8217;t be able to do so if you didn&#8217;t do anything.</p>
<p>I&#8217;ve seen several approaches to this so far, but they often hard code a certain position of the view or sizes. Like assuming that the covered view always reaches towards the bottom of the screen or always has a certain amount of space taken away from it by the status bar, navigation bar and possibly toolbar.</p>
<p>The whole thing gets even more complicated by the fact the the coordinate system of the app&#8217;s window is always in portrait even though your app rotates. So is the frame of the keyboard which you can get from an info dictionary in several notifications. I&#8217;ll show you the most universally working method I was able to come up with.</p>
<p><span id="more-5249"></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>The first part is obvious, you want to subscribe to two notifications, one for when the keyboard has fully animated in and one for when the keyboard will go away. I&#8217;ve seen people mess with the frame of the covered view, but I generally found this to be disturbing the contents, in the least causing an unnecessary redraw because of the bounds change.</p>
<p>Instead I prefer to set the content inset of the scroll view. This does not affect the contents, but permits for additional scroll distance so that the content at the bottom edge can be scrolled into the visible area above the keyboard. The inset for the scroll indicator is separate but needs the same treatment.</p>
<p>Note that all this is best done in your UIScrollView subclass.</p>

<div class="wp_codebox"><table><tr id="p524993"><td class="code" id="p5249code93"><pre class="objc" style="font-family:monospace;"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/"><span style="color: #400080;">NSNotificationCenter</span></a> <span style="color: #002200;">*</span>center <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/"><span style="color: #400080;">NSNotificationCenter</span></a> defaultCenter<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>center addObserver<span style="color: #002200;">:</span>self selector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>keyboardDidShow<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span> 
       name<span style="color: #002200;">:</span>UIKeyboardDidShowNotification object<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>center addObserver<span style="color: #002200;">:</span>self selector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>keyboardWillHide<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span> 
       name<span style="color: #002200;">:</span>UIKeyboardWillHideNotification object<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>And of course we remove the observer in the dealloc.</p>

<div class="wp_codebox"><table><tr id="p524994"><td class="code" id="p5249code94"><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>dealloc
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/"><span style="color: #400080;">NSNotificationCenter</span></a> defaultCenter<span style="color: #002200;">&#93;</span> removeObserver<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>When the keyboard is hidden we don&#8217;t want any insets, so we reset them to zero.</p>

<div class="wp_codebox"><table><tr id="p524995"><td class="code" id="p5249code95"><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>keyboardWillHide<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>
	self.contentInset <span style="color: #002200;">=</span> UIEdgeInsetsMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</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>;
	self.scrollIndicatorInsets <span style="color: #002200;">=</span> self.contentInset;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>And now the good part, calculating the correct covered area of the view, regardless of where it is positioned on screen. Yet another complication derives from the fact that if we use the scrollview&#8217;s coordinate system then we get different results depending on the content size. </p>
<p>So instead we need to use the superview&#8217;s coordinate system for transforming to and from the window coordinate system. This is necessary because the keyboard is mounted on the window and thus also has window coordinates.</p>

<div class="wp_codebox"><table><tr id="p524996"><td class="code" id="p5249code96"><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>keyboardDidShow<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>
	<span style="color: #11740a; font-style: italic;">// keyboard frame is in window coordinates</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>userInfo <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>notification userInfo<span style="color: #002200;">&#93;</span>;
	CGRect keyboardFrame <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>userInfo objectForKey<span style="color: #002200;">:</span>UIKeyboardFrameEndUserInfoKey<span style="color: #002200;">&#93;</span> CGRectValue<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// convert own frame to window coordinates, frame is in superview's coordinates</span>
	CGRect ownFrame <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self.window convertRect<span style="color: #002200;">:</span>self.frame fromView<span style="color: #002200;">:</span>self.superview<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// calculate the area of own frame that is covered by keyboard</span>
	CGRect coveredFrame <span style="color: #002200;">=</span> CGRectIntersection<span style="color: #002200;">&#40;</span>ownFrame, keyboardFrame<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// now this might be rotated, so convert it back</span>
	coveredFrame <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self.window convertRect<span style="color: #002200;">:</span>coveredFrame toView<span style="color: #002200;">:</span>self.superview<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// set inset to make up for covered array at bottom</span>
	self.contentInset <span style="color: #002200;">=</span> UIEdgeInsetsMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span>, coveredFrame.size.height, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>;
	self.scrollIndicatorInsets <span style="color: #002200;">=</span> self.contentInset;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>We use the handy CGRectIntersection function to get a rectangle that is common to both the keyboard and view frame. Since there might have been a rotation transform somewhere in between, we also need to convert back to our original superview&#8217;s coordinate system. And that&#8217;s it, now coveredFrame gives us exactly the area of our view that is covered and thus the hight is also the bottom inset we need to apply.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5249&amp;md5=7aaa614bd4aadc3a2a339c187c42ac33" 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/07/calculating-area-covered-by-keyboard/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5249&amp;md5=7aaa614bd4aadc3a2a339c187c42ac33" type="text/html" />"
	</item>
		<item>
		<title>How to Simulate Cellular Connections on Your Mac</title>
		<link>http://www.cocoanetics.com/2011/06/how-to-simulate-cellular-connections-on-your-mac/</link>
		<comments>http://www.cocoanetics.com/2011/06/how-to-simulate-cellular-connections-on-your-mac/#comments</comments>
		<pubDate>Thu, 16 Jun 2011 10:45:26 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5181</guid>
		<description><![CDATA[If you are making your application real-life-proof you will also have to deal with diminished or dropped connectivity. I already discussed how to detect the kind of connectivity your app is having at present. But another real-life restriction stems from slower bandwidths available over cellular connections, especially if you have no 3G reception. Even Long of Scribd showed me this trick I am about to explain here. This enables you to artificially create a bottleneck on your connection so that you can test how the app behaves when only cellular bandwidth is available. This helps you to see if your custom progress bar is showing nicely or possibly if your progressive image is indeed progressive. Also this might reveal synchronous URL loading operations that you should never ever do in production apps. Label Buy an ad here Readability I would expect for Apple to add this artificial bandwidth limiting to iPhone Simulator, but until they do you heres a method to achieve this yourself. This is my regular network connection, please don&#8217;t laugh if you are used to higher speeds. Now our trick creates a new IP firewall rule restricting the bandwidth to 112 kBits. You have to do this modification as root, hence the sudo and the first sudo will ask for your root password. sudo ipfw add 500 pipe 1 ip from any to any sudo ipfw pipe 1 config bw 112kbit/s plr 0 delay 20ms The same speed test shows the much decreased connectivity: Now you can test your app in simulator and enjoy the much faster turnaround when debugging the handling of slow connections. To remove the firewall rule you use the following command: sudo ipfw delete 500 This is a very handy trick to have in your arsenal. As I said many of the usability problems of production apps result from synchronous network operations as well as not having though through how to deal with slow connections. But these are a fact of life, so you better make sure that your apps can deal with them gracefully. Update, a few minutes after the first post &#8230; Now having so many smart readers of this here blog also means that often they know of smarter ways to achieve the same things. If you have Charles Debugging Proxy you already have a speed limiter built into that. Another alternative that four people recommended independently is the speed limit preference pane by Mike Schrag which has the added advantage of allowing easy configuring for specific domains. Both are comfortable alternate solutions, but I can never hurt knowing how to achieve the same thing in termal. Still, thanks for all the suggestions!]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/06/how-to-simulate-cellular-connections-on-your-mac/"></g:plusone></div><p>If you are making your application real-life-proof you will also have to deal with diminished or dropped connectivity. I already discussed how to <a title="Reachability" href="http://www.cocoanetics.com/2010/08/reachability/">detect the kind of connectivity</a> your app is having at present.</p>
<p>But another real-life restriction stems from slower bandwidths available over cellular connections, especially if you have no 3G reception. Even Long of Scribd showed me this trick I am about to explain here. This enables you to artificially create a bottleneck on your connection so that you can test how the app behaves when only cellular bandwidth is available.</p>
<p>This helps you to see if your custom progress bar is showing nicely or possibly if your progressive image is indeed progressive. Also this might reveal synchronous URL loading operations that you should never ever do in production apps.</p>
<p><span id="more-5181"></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>I would expect for Apple to add this artificial bandwidth limiting to iPhone Simulator, but until they do you heres a method to achieve this yourself. This is my regular network connection, please don&#8217;t laugh if you are used to higher speeds.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-06-16-at-12.21.14-PM.png"><img class="alignnone size-full wp-image-5182" title="Speed (normal)" src="http://www.cocoanetics.com/files/Screen-Shot-2011-06-16-at-12.21.14-PM.png" alt="" width="421" height="56" /></a></p>
<p>Now our trick creates a new IP firewall rule restricting the bandwidth to 112 kBits. You have to do this modification as root, hence the sudo and the first sudo will ask for your root password.</p>

<div class="wp_codebox"><table><tr id="p518199"><td class="code" id="p5181code99"><pre class="sh" style="font-family:monospace;">sudo ipfw add 500 pipe 1 ip from any to any
sudo ipfw pipe 1 config bw 112kbit/s plr 0 delay 20ms</pre></td></tr></table></div>

<p>The same speed test shows the much decreased connectivity:</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-06-16-at-12.31.21-PM.png"><img class="alignnone size-full wp-image-5183" title="Speed (limited)" src="http://www.cocoanetics.com/files/Screen-Shot-2011-06-16-at-12.31.21-PM.png" alt="" width="407" height="54" /></a></p>
<p>Now you can test your app in simulator and enjoy the much faster turnaround when debugging the handling of slow connections.</p>
<p>To remove the firewall rule you use the following command:</p>

<div class="wp_codebox"><table><tr id="p5181100"><td class="code" id="p5181code100"><pre class="sh" style="font-family:monospace;">sudo ipfw delete 500</pre></td></tr></table></div>

<p>This is a very handy trick to have in your arsenal. As I said many of the usability problems of production apps result from synchronous network operations as well as not having though through how to deal with slow connections. But these are a fact of life, so you better make sure that your apps can deal with them gracefully.</p>
<p>Update, a few minutes after the first post &#8230;</p>
<p>Now having so many smart readers of this here blog also means that often they know of smarter ways to achieve the same things. If you have <a title="How to Spy on the Web Traffic of any App" href="http://www.cocoanetics.com/2010/12/how-to-spy-on-the-web-traffic-of-any-app/">Charles Debugging Proxy</a> you already have a speed limiter built into that.</p>
<p>Another alternative that four people recommended independently is the <a href="http://mschrag.github.com/">speed limit preference pane </a>by Mike Schrag which has the added advantage of allowing easy configuring for specific domains.</p>
<p><a href="http://www.cocoanetics.com/files/SpeedLimit.png"><img class="alignnone size-full wp-image-5189" title="SpeedLimit" src="http://www.cocoanetics.com/files/SpeedLimit.png" alt="" width="449" height="200" /></a></p>
<p>Both are comfortable alternate solutions, but I can never hurt knowing how to achieve the same thing in termal.</p>
<p>Still, thanks for all the suggestions!</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5181&amp;md5=fec3f0fe58b0c2f86d8431b6af91e80c" 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/06/how-to-simulate-cellular-connections-on-your-mac/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5181&amp;md5=fec3f0fe58b0c2f86d8431b6af91e80c" type="text/html" />"
	</item>
		<item>
		<title>Free Range</title>
		<link>http://www.cocoanetics.com/2011/05/free-range/</link>
		<comments>http://www.cocoanetics.com/2011/05/free-range/#comments</comments>
		<pubDate>Tue, 31 May 2011 19:58:33 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5138</guid>
		<description><![CDATA[You will often find yourself working with NSRange parameters and variables, especially when dealing with strings. I stumbled into a problem that I think is an SDK bug, that prompted me to look at the header and find out what kind of functions are provided to us for comfortably dealing with NSRange. Label Buy an ad here Readability Don&#8217;t be fooled by the NS to think that this is an object. Similar to NSInteger this is just a scalar value, basically shorthand for the compiler to know that there are two components &#8211; location and length &#8211; with 4 bytes each. So if you access range.length you are interested in the second 4 bytes, for range.location you access the first 4. This also means that you don&#8217;t have any instance methods available, all manipulation of NSRange has to be via C-style functions. So let&#8217;s have a look at the NSRange.h header contained in the Foundation.framework to see what interesting functions await for us to be unearthed there. In fact, let me print the entire header and let&#8217;s read it together. typedef struct _NSRange &#123; NSUInteger location; NSUInteger length; &#125; NSRange; This is how the NSRange is defined as a type. Types are what you need to define variables. You can see that NSRange consists of two unsigned integers. typedef NSRange *NSRangePointer; In some instances you might not deal with an NSRange directly, but with a pointer to 8 bytes of memory containing an NSRange. Instead of writing NSRange *every time, Apple defines an NSRangePointer for us to use. Since these are a couple more characters to type then the only reason I can think of is safety. Using NSRangePointer avoids the risk of forgetting the asterisk. NS_INLINE NSRange NSMakeRange&#40;NSUInteger loc, NSUInteger len&#41; &#123; NSRange r; r.location = loc; r.length = len; return r; &#125; This is the most convenient way to fill an NSRange with values. It is defined as inline which means that this actual code is inserted into yours everywhere you use it as opposed to being execute as a true function call, which would involve copying stuff onto the stack, jumping to code, copying the result back and jumping again. Inlining happens transparently to you, but gives you the better performance of avoiding the function call. This usually makes sense for very small functions like this one. NS_INLINE NSUInteger NSMaxRange&#40;NSRange range&#41; &#123; return &#40;range.location + range.length&#41;; &#125; This is neat, using this inline function we don&#8217;t have to do the addition ourselves to find the maximum index contained in the range. NS_INLINE BOOL NSLocationInRange&#40;NSUInteger loc, NSRange range&#41; &#123; return &#40;loc - range.location &#60; range.length&#41;; &#125; Another neat inline function lets us check if an index is contained in the range. NS_INLINE BOOL NSEqualRanges&#40;NSRange range1, NSRange range2&#41; &#123; return &#40;range1.location == range2.location &#38;&#38; range1.length == range2.length&#41;; &#125; This saves us even more work if we wanted to see if two ranges are identical. FOUNDATION_EXPORT NSRange NSUnionRange&#40;NSRange range1, NSRange range2&#41;; This creates a union of two ranges. The code for this is actually contained in one binary of the Foundation framework. The resulting union will go from the smallest location to include the maximum index. So if you create a union of two non-intersecting ranges the result also covers the space between the ranges. FOUNDATION_EXPORT NSRange NSIntersectionRange&#40;NSRange range1, NSRange range2&#41;; This makes an intersection. This works only if the ranges are overlapping. If they don&#8217;t then {0,0} is returned. Knowing this we can easily check if one range is contained within another by creating an intersection and then checking if length is non-zero. FOUNDATION_EXPORT NSString *NSStringFromRange&#40;NSRange range&#41;; If we needed a string representation of a range, then this function would quickly provide it for you. Use in NSLog for example. FOUNDATION_EXPORT NSRange NSRangeFromString&#40;NSString *aString&#41;; In some even rarer cases you might want to do the reverse, move from NSString to NSRange. This is the function to achieve that. @interface NSValue &#40;NSValueRangeExtensions&#41; &#160; + &#40;NSValue *&#41;valueWithRange:&#40;NSRange&#41;range; - &#40;NSRange&#41;rangeValue; &#160; @end And the final block defines a category for NSValue to package NSRanges into objects for storing for whenever you need to have an Objective-C object, like if you want to store multiple ranges in an array. Now, about the bug that I suspect to have found. NSAttributedString has a method to enumerate over all the attribute dictionaries and you get an NSRange for where this attributes are valid. enumerateAttributesInRange:options:usingBlock: This usually works without problems unless you run into a low-memory condition. Apparently there is a situation when this method returns a range outside of the string. So this is how I worked around it to avoid problems. NSRange validRange = NSMakeRange&#40;0, &#91;attributedString length&#93;&#41;; &#160; &#91;attributedString enumerateAttributesInRange:range options:0 usingBlock: ^&#40;NSDictionary *attrs, NSRange range, BOOL *stop&#41; &#123; if &#40;NSIntersectionRange&#40;range, validRange&#41;.length&#41; &#123; // work with attributes &#125; else &#123; NSLog&#40;@&#34;Invalid Range returned by [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/05/free-range/"></g:plusone></div><p>You will often find yourself working with NSRange parameters and variables, especially when dealing with strings. I stumbled into a problem that I think is an SDK bug, that prompted me to look at the header and find out what kind of functions are provided to us for comfortably dealing with NSRange.</p>
<p><span id="more-5138"></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>Don&#8217;t be fooled by the NS to think that this is an object. Similar to NSInteger this is just a scalar value, basically shorthand for the compiler to know that there are two components &#8211; location and length &#8211; with 4 bytes each. So if you access range.length you are interested in the second 4 bytes, for range.location you access the first 4.</p>
<p>This also means that you don&#8217;t have any instance methods available, all manipulation of NSRange has to be via C-style functions. So let&#8217;s have a look at the NSRange.h header contained in the Foundation.framework to see what interesting functions await for us to be unearthed there.</p>
<p>In fact, let me print the entire header and let&#8217;s read it together.</p>

<div class="wp_codebox"><table><tr id="p5138113"><td class="code" id="p5138code113"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">typedef</span> <span style="color: #a61390;">struct</span> _NSRange <span style="color: #002200;">&#123;</span>
    NSUInteger location;
    NSUInteger length;
<span style="color: #002200;">&#125;</span> <span style="color: #a61390;">NSRange</span>;</pre></td></tr></table></div>

<p>This is how the NSRange is defined as a type. Types are what you need to define variables. You can see that NSRange consists of two unsigned integers.</p>

<div class="wp_codebox"><table><tr id="p5138114"><td class="code" id="p5138code114"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">typedef</span> <span style="color: #a61390;">NSRange</span> <span style="color: #002200;">*</span>NSRangePointer;</pre></td></tr></table></div>

<p>In some instances you might not deal with an NSRange directly, but with a pointer to 8 bytes of memory containing an NSRange. Instead of writing NSRange *every time, Apple defines an NSRangePointer for us to use. Since these are a couple more characters to type then the only reason I can think of is safety. Using NSRangePointer avoids the risk of forgetting the asterisk.</p>

<div class="wp_codebox"><table><tr id="p5138115"><td class="code" id="p5138code115"><pre class="objc" style="font-family:monospace;">NS_INLINE <span style="color: #a61390;">NSRange</span> NSMakeRange<span style="color: #002200;">&#40;</span>NSUInteger loc, NSUInteger len<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">NSRange</span> r;
    r.location <span style="color: #002200;">=</span> loc;
    r.length <span style="color: #002200;">=</span> len;
    <span style="color: #a61390;">return</span> r;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This is the most convenient way to fill an NSRange with values. It is defined as inline which means that this actual code is inserted into yours everywhere you use it as opposed to being execute as a true function call, which would involve copying stuff onto the stack, jumping to code, copying the result back and jumping again. Inlining happens transparently to you, but gives you the better performance of avoiding the function call. This usually makes sense for very small functions like this one.</p>

<div class="wp_codebox"><table><tr id="p5138116"><td class="code" id="p5138code116"><pre class="objc" style="font-family:monospace;">NS_INLINE NSUInteger NSMaxRange<span style="color: #002200;">&#40;</span><span style="color: #a61390;">NSRange</span> range<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">return</span> <span style="color: #002200;">&#40;</span>range.location <span style="color: #002200;">+</span> range.length<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This is neat, using this inline function we don&#8217;t have to do the addition ourselves to find the maximum index contained in the range.</p>

<div class="wp_codebox"><table><tr id="p5138117"><td class="code" id="p5138code117"><pre class="objc" style="font-family:monospace;">NS_INLINE <span style="color: #a61390;">BOOL</span> NSLocationInRange<span style="color: #002200;">&#40;</span>NSUInteger loc, <span style="color: #a61390;">NSRange</span> range<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">return</span> <span style="color: #002200;">&#40;</span>loc <span style="color: #002200;">-</span> range.location &lt; range.length<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Another neat inline function lets us check if an index is contained in the range.</p>

<div class="wp_codebox"><table><tr id="p5138118"><td class="code" id="p5138code118"><pre class="objc" style="font-family:monospace;">NS_INLINE <span style="color: #a61390;">BOOL</span> NSEqualRanges<span style="color: #002200;">&#40;</span><span style="color: #a61390;">NSRange</span> range1, <span style="color: #a61390;">NSRange</span> range2<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">return</span> <span style="color: #002200;">&#40;</span>range1.location <span style="color: #002200;">==</span> range2.location <span style="color: #002200;">&amp;&amp;</span> range1.length <span style="color: #002200;">==</span> range2.length<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This saves us even more work if we wanted to see if two ranges are identical.</p>

<div class="wp_codebox"><table><tr id="p5138119"><td class="code" id="p5138code119"><pre class="objc" style="font-family:monospace;">FOUNDATION_EXPORT <span style="color: #a61390;">NSRange</span> NSUnionRange<span style="color: #002200;">&#40;</span><span style="color: #a61390;">NSRange</span> range1, <span style="color: #a61390;">NSRange</span> range2<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>This creates a union of two ranges. The code for this is actually contained in one binary of the Foundation framework. The resulting union will go from the smallest location to include the maximum index. So if you create a union of two non-intersecting ranges the result also covers the space between the ranges.</p>

<div class="wp_codebox"><table><tr id="p5138120"><td class="code" id="p5138code120"><pre class="objc" style="font-family:monospace;">FOUNDATION_EXPORT <span style="color: #a61390;">NSRange</span> NSIntersectionRange<span style="color: #002200;">&#40;</span><span style="color: #a61390;">NSRange</span> range1, <span style="color: #a61390;">NSRange</span> range2<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>This makes an intersection. This works only if the ranges are overlapping. If they don&#8217;t then {0,0} is returned. Knowing this we can easily check if one range is contained within another by  creating an intersection and then checking if length is non-zero.</p>

<div class="wp_codebox"><table><tr id="p5138121"><td class="code" id="p5138code121"><pre class="objc" style="font-family:monospace;">FOUNDATION_EXPORT <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>NSStringFromRange<span style="color: #002200;">&#40;</span><span style="color: #a61390;">NSRange</span> range<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>If we needed a string representation of a range, then this function would quickly provide it for you. Use in NSLog for example.</p>

<div class="wp_codebox"><table><tr id="p5138122"><td class="code" id="p5138code122"><pre class="objc" style="font-family:monospace;">FOUNDATION_EXPORT <span style="color: #a61390;">NSRange</span> NSRangeFromString<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>aString<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>In some even rarer cases you might want to do the reverse, move from NSString to NSRange. This is the function to achieve that.</p>

<div class="wp_codebox"><table><tr id="p5138123"><td class="code" id="p5138code123"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSValue_Class/"><span style="color: #400080;">NSValue</span></a> <span style="color: #002200;">&#40;</span>NSValueRangeExtensions<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/NSValue_Class/"><span style="color: #400080;">NSValue</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>valueWithRange<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">NSRange</span><span style="color: #002200;">&#41;</span>range;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">NSRange</span><span style="color: #002200;">&#41;</span>rangeValue;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>And the final block defines a category for NSValue to package NSRanges into objects for storing for whenever you need to have an Objective-C object, like if you want to store multiple ranges in an array. </p>
<p>Now, about the bug that I suspect to have found. NSAttributedString has a method to enumerate over all the attribute dictionaries and you get an NSRange for where this attributes are valid. enumerateAttributesInRange:options:usingBlock:</p>
<p>This usually works without problems unless you run into a low-memory condition. Apparently there is a situation when this method returns a range outside of the string. So this is how I worked around it to avoid problems.</p>

<div class="wp_codebox"><table><tr id="p5138124"><td class="code" id="p5138code124"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">NSRange</span> validRange <span style="color: #002200;">=</span> NSMakeRange<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #002200;">&#91;</span>attributedString length<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>attributedString enumerateAttributesInRange<span style="color: #002200;">:</span>range options<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span> usingBlock<span style="color: #002200;">:</span>
         <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>attrs, <span style="color: #a61390;">NSRange</span> range, <span style="color: #a61390;">BOOL</span> <span style="color: #002200;">*</span>stop<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
         <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>NSIntersectionRange<span style="color: #002200;">&#40;</span>range, validRange<span style="color: #002200;">&#41;</span>.length<span style="color: #002200;">&#41;</span>
         <span style="color: #002200;">&#123;</span>
                  <span style="color: #11740a; font-style: italic;">// work with attributes</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;Invalid Range returned by attribute enumeration: %@&quot;</span>, NSStringFromRange<span style="color: #002200;">&#40;</span>range<span style="color: #002200;">&#41;</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>So if the value returned from the enumeration is outside of the valid range then I ignore it.</p>
<p>Knowing of these functions allows you to more efficiently deal with NSRanges. So you might want to commit these to memory or make a mental or actual bookmark of this article. </p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5138&amp;md5=808db75fc6b75152c7ab9eba45ca3163" 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/05/free-range/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5138&amp;md5=808db75fc6b75152c7ab9eba45ca3163" type="text/html" />"
	</item>
		<item>
		<title>And Now Lazy Loading with NSURLConnection</title>
		<link>http://www.cocoanetics.com/2011/05/and-now-lazy-loading-with-nsurlconnection/</link>
		<comments>http://www.cocoanetics.com/2011/05/and-now-lazy-loading-with-nsurlconnection/#comments</comments>
		<pubDate>Mon, 23 May 2011 06:51:29 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5073</guid>
		<description><![CDATA[In my previous post I demonstrated how to quickly whip up some lazy loading for a UIImageView. Today I revamped it to use NSURLConnection instead, because this would allow for cancelling the request. It also gives us the option of specifying if we want to make use of the cache and also how long we&#8217;re actually willing to wait for an answer. That sounds more straightforward than it actually is. If you simply use an NSURLConnection with its delegate methods then you might not see anything wrong, unless you are using this lazy image view as subview of a UIScrollView. The problem there is that the scroll view blocks the run loop and so your connection events will not get delivered until you lift the finger. But I found a solution for that. Let me know in the comments if you think something could be done in a more elegant way. The code for this is available in the NSAttributedString+HTML project. Label Buy an ad here Readability DTLazyImageView.h @interface DTLazyImageView : UIImageView &#123; NSURL *_url; &#160; NSURLConnection *_connection; NSMutableData *_receivedData; &#125; &#160; @property &#40;nonatomic, retain&#41; NSURL *url; &#160; - &#40;void&#41;cancelLoading; &#160; @end DTLazyImageView.m #import &#34;DTLazyImageView.h&#34; &#160; &#160; @implementation DTLazyImageView &#160; - &#40;void&#41;dealloc &#123; self.image = nil; &#91;_url release&#93;; &#160; &#91;_receivedData release&#93;; &#91;_connection cancel&#93;; &#91;_connection release&#93;; &#160; &#91;super dealloc&#93;; &#125; &#160; - &#40;void&#41;loadImageAtURL:&#40;NSURL *&#41;url &#123; NSAutoreleasePool *pool = &#91;&#91;NSAutoreleasePool alloc&#93; init&#93;; &#160; NSURLRequest *request = &#91;&#91;NSURLRequest alloc&#93; initWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10.0&#93;; _connection = &#91;&#91;NSURLConnection alloc&#93; initWithRequest:request delegate:self startImmediately:YES&#93;; &#91;request release&#93;; &#160; // so that our connection events get processed even if a scrollview blocks the main run loop CFRunLoopRun&#40;&#41;; &#91;pool release&#93;; &#125; &#160; - &#40;void&#41;didMoveToSuperview &#123; if &#40;!self.image &#38;&#38; _url &#38;&#38; !_connection&#41; &#123; //[self loadImageAtURL:_url]; &#91;self performSelectorInBackground:@selector&#40;loadImageAtURL:&#41; withObject:_url&#93;; &#125; &#125; &#160; - &#40;void&#41;cancelLoading &#123; &#91;_connection cancel&#93;; &#91;_connection release&#93;, _connection = nil; &#160; &#91;_receivedData release&#93;, _receivedData = nil; &#160; CFRunLoopStop&#40;CFRunLoopGetCurrent&#40;&#41;&#41;; &#125; &#160; #pragma mark NSURL Loading &#160; - &#40;void&#41;connection:&#40;NSURLConnection *&#41;connection didReceiveResponse:&#40;NSURLResponse *&#41;response &#123; // every time we get an response it might be a forward, so we discard what data we have &#91;_receivedData release&#93;, _receivedData = nil; &#160; // does not fire for local file URLs if &#40;&#91;response isKindOfClass:&#91;NSHTTPURLResponse class&#93;&#93;&#41; &#123; NSHTTPURLResponse *httpResponse = &#40;id&#41;response; &#160; if &#40;!&#91;&#91;httpResponse MIMEType&#93; hasPrefix:@&#34;image&#34;&#93;&#41; &#123; &#91;self cancelLoading&#93;; &#125; &#125; &#160; _receivedData = &#91;&#91;NSMutableData alloc&#93; init&#93;; &#125; &#160; - &#40;void&#41;connection:&#40;NSURLConnection *&#41;connection didReceiveData:&#40;NSData *&#41;data &#123; &#91;_receivedData appendData:data&#93;; &#125; &#160; - &#40;void&#41;connectionDidFinishLoading:&#40;NSURLConnection *&#41;connection &#123; if &#40;_receivedData&#41; &#123; UIImage *image = &#91;&#91;UIImage alloc&#93; initWithData:_receivedData&#93;; &#160; //self.image = image; &#91;self performSelectorOnMainThread:@selector&#40;setImage:&#41; withObject:image waitUntilDone:YES&#93;; &#160; &#91;image release&#93;; &#160; &#91;_receivedData release&#93;, _receivedData = nil; &#125; &#160; &#91;_connection release&#93;, _connection = nil; &#160; CFRunLoopStop&#40;CFRunLoopGetCurrent&#40;&#41;&#41;; &#125; &#160; - &#40;void&#41;connection:&#40;NSURLConnection *&#41;connection didFailWithError:&#40;NSError *&#41;error &#123; NSLog&#40;@&#34;Failed to load image at %@, %@&#34;, _url, &#91;error localizedDescription&#93;&#41;; &#160; &#91;_connection release&#93;, _connection = nil; &#91;_receivedData release&#93;, _receivedData = nil; &#160; CFRunLoopStop&#40;CFRunLoopGetCurrent&#40;&#41;&#41;; &#125; &#160; &#160; #pragma mark Properties &#160; @synthesize url = _url; &#160; @end The trick is to use CFRunLoopRun to have a new run loop to take care of delivering the events for this NSURLConnection. If you use that you also have to stop it if it&#8217;s no longer needed. There are now 3 places where this is the case: successful loading, error and canceling. This also shows how you can check the MIME type of the received data, because you might want to cancel the operation if it is not an image you are getting back. I found that I needed to combine this approach with running the NSURLConnection on a background thread because otherwise there would be unwanted side effects impacting the tracking in my UIScrollView. As I mentioned before, I&#8217;m on shaky territory as I have never messed with run loops before. So please tell me if there&#8217;s some problem with this approach. &#8230; and so Nyxouf did, his suggestion in the comments allowed me to remove quite a few lines of this nasty code after I found this to be working just as well. The trick seems to be to not have the connection start right away, but first schedule it on the current run loop for the common modes and then start it. DTLazyImageView.m #import &#34;DTLazyImageView.h&#34; &#160; &#160; @implementation DTLazyImageView &#160; - &#40;void&#41;dealloc &#123; self.image = nil; &#91;_url release&#93;; &#160; &#91;_receivedData release&#93;; &#91;_connection cancel&#93;; &#91;_connection release&#93;; &#160; &#91;super dealloc&#93;; &#125; &#160; - &#40;void&#41;loadImageAtURL:&#40;NSURL *&#41;url &#123; NSURLRequest *request = &#91;&#91;NSURLRequest alloc&#93; initWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10.0&#93;; &#160; _connection = &#91;&#91;NSURLConnection alloc&#93; initWithRequest:request delegate:self startImmediately:NO&#93;; &#91;_connection scheduleInRunLoop:&#91;NSRunLoop currentRunLoop&#93; forMode:NSRunLoopCommonModes&#93;; &#91;_connection start&#93;; &#160; &#91;request release&#93;; &#125; &#160; - &#40;void&#41;didMoveToSuperview &#123; if &#40;!self.image &#38;&#38; _url &#38;&#38; !_connection&#41; &#123; &#91;self loadImageAtURL:_url&#93;; &#125; &#125; &#160; - &#40;void&#41;cancelLoading &#123; &#91;_connection cancel&#93;; &#91;_connection release&#93;, _connection = nil; &#160; &#91;_receivedData release&#93;, _receivedData = nil; &#125; &#160; #pragma mark NSURL Loading &#160; - &#40;void&#41;connection:&#40;NSURLConnection *&#41;connection didReceiveResponse:&#40;NSURLResponse *&#41;response &#123; // every time we get an response it might be a forward, so we discard what data we have [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/05/and-now-lazy-loading-with-nsurlconnection/"></g:plusone></div><p>In my <a title="A Quick Lazy-Loading UIImageView" href="http://www.cocoanetics.com/2011/05/a-quick-lazy-loading-uiimageview/">previous post</a> I demonstrated how to quickly whip up some lazy loading for a UIImageView. Today I revamped it to use NSURLConnection instead, because this would allow for cancelling the request. It also gives us the option of specifying if we want to make use of the cache and also how long we&#8217;re actually willing to wait for an answer.</p>
<p>That sounds more straightforward than it actually is. If you simply use an NSURLConnection with its delegate methods then you might not see anything wrong, unless you are using this lazy image view as subview of a UIScrollView. The problem there is that the scroll view blocks the run loop and so your connection events will not get delivered until you lift the finger.</p>
<p>But I <a href="http://stackoverflow.com/questions/1728631/asynchronous-request-to-the-server-from-background-thread">found a solution</a> for that. Let me know in the comments if you think something could be done in a more elegant way. The code for this is available in the <a href="github.com/Cocoanetics/NSAttributedString-Additions-for-HTML">NSAttributedString+HTML project</a>.</p>
<p><span id="more-5073"></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p><strong>DTLazyImageView.h</strong></p>

<div class="wp_codebox"><table><tr id="p5073128"><td class="code" id="p5073code128"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> DTLazyImageView <span style="color: #002200;">:</span> UIImageView 
<span style="color: #002200;">&#123;</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>_url;
&nbsp;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/"><span style="color: #400080;">NSURLConnection</span></a> <span style="color: #002200;">*</span>_connection;
	<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>_receivedData;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</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>url;
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>cancelLoading;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p><strong>DTLazyImageView.m</strong></p>

<div class="wp_codebox"><table><tr id="p5073129"><td class="code" id="p5073code129"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;DTLazyImageView.h&quot;</span>
&nbsp;
&nbsp;
<span style="color: #a61390;">@implementation</span> DTLazyImageView
&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>
	self.image <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
	<span style="color: #002200;">&#91;</span>_url release<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>_receivedData release<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>_connection cancel<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>_connection release<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>super dealloc<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>loadImageAtURL<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</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><span style="color: #002200;">&#41;</span>url
<span style="color: #002200;">&#123;</span>
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/"><span style="color: #400080;">NSAutoreleasePool</span></a> <span style="color: #002200;">*</span>pool <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/NSAutoreleasePool_Class/"><span style="color: #400080;">NSAutoreleasePool</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
&nbsp;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/"><span style="color: #400080;">NSURLRequest</span></a> <span style="color: #002200;">*</span>request <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/NSURLRequest_Class/"><span style="color: #400080;">NSURLRequest</span></a> alloc<span style="color: #002200;">&#93;</span> initWithURL<span style="color: #002200;">:</span>url 
				cachePolicy<span style="color: #002200;">:</span>NSURLRequestReturnCacheDataElseLoad timeoutInterval<span style="color: #002200;">:</span><span style="color: #2400d9;">10.0</span><span style="color: #002200;">&#93;</span>;
	_connection <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/NSURLConnection_Class/"><span style="color: #400080;">NSURLConnection</span></a> alloc<span style="color: #002200;">&#93;</span> initWithRequest<span style="color: #002200;">:</span>request delegate<span style="color: #002200;">:</span>self
				 startImmediately<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>request release<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// so that our connection events get processed even if a scrollview blocks the main run loop</span>
	CFRunLoopRun<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>; 
	<span style="color: #002200;">&#91;</span>pool release<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>didMoveToSuperview
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>self.image <span style="color: #002200;">&amp;&amp;</span> _url <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">!</span>_connection<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #11740a; font-style: italic;">//[self loadImageAtURL:_url];</span>
		<span style="color: #002200;">&#91;</span>self performSelectorInBackground<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>loadImageAtURL<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span> withObject<span style="color: #002200;">:</span>_url<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>cancelLoading
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>_connection cancel<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>_connection release<span style="color: #002200;">&#93;</span>, _connection <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>_receivedData release<span style="color: #002200;">&#93;</span>, _receivedData <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
	CFRunLoopStop<span style="color: #002200;">&#40;</span>CFRunLoopGetCurrent<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#pragma mark NSURL Loading</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>connection<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/"><span style="color: #400080;">NSURLConnection</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>connection didReceiveResponse<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLResponse_Class/"><span style="color: #400080;">NSURLResponse</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>response
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// every time we get an response it might be a forward, so we discard what data we have</span>
	<span style="color: #002200;">&#91;</span>_receivedData release<span style="color: #002200;">&#93;</span>, _receivedData <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// does not fire for local file URLs</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>response isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPURLResponse_Class/"><span style="color: #400080;">NSHTTPURLResponse</span></a> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<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>httpResponse <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>response;
&nbsp;
		<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>httpResponse MIMEType<span style="color: #002200;">&#93;</span> hasPrefix<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
		<span style="color: #002200;">&#123;</span>
			<span style="color: #002200;">&#91;</span>self cancelLoading<span style="color: #002200;">&#93;</span>;
		<span style="color: #002200;">&#125;</span>
	<span style="color: #002200;">&#125;</span>
&nbsp;
	_receivedData <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>;
<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>connection<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/"><span style="color: #400080;">NSURLConnection</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>connection didReceiveData<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
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>_receivedData appendData<span style="color: #002200;">:</span>data<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>connectionDidFinishLoading<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/"><span style="color: #400080;">NSURLConnection</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>connection
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>_receivedData<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		UIImage <span style="color: #002200;">*</span>image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIImage alloc<span style="color: #002200;">&#93;</span> initWithData<span style="color: #002200;">:</span>_receivedData<span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #11740a; font-style: italic;">//self.image = image;</span>
		<span style="color: #002200;">&#91;</span>self performSelectorOnMainThread<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>setImage<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span> withObject<span style="color: #002200;">:</span>image 
				waitUntilDone<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #002200;">&#91;</span>image release<span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #002200;">&#91;</span>_receivedData release<span style="color: #002200;">&#93;</span>, _receivedData <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #002200;">&#91;</span>_connection release<span style="color: #002200;">&#93;</span>, _connection <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
	CFRunLoopStop<span style="color: #002200;">&#40;</span>CFRunLoopGetCurrent<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</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><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>connection<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/"><span style="color: #400080;">NSURLConnection</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>connection didFailWithError<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>error
<span style="color: #002200;">&#123;</span>
	NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Failed to load image at %@, %@&quot;</span>, _url, <span style="color: #002200;">&#91;</span>error localizedDescription<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>_connection release<span style="color: #002200;">&#93;</span>, _connection <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
	<span style="color: #002200;">&#91;</span>_receivedData release<span style="color: #002200;">&#93;</span>, _receivedData <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
	CFRunLoopStop<span style="color: #002200;">&#40;</span>CFRunLoopGetCurrent<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #6e371a;">#pragma mark Properties</span>
&nbsp;
<span style="color: #a61390;">@synthesize</span> url <span style="color: #002200;">=</span> _url;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>The trick is to use CFRunLoopRun to have a new run loop to take care of delivering the events for this NSURLConnection. If you use that you also have to stop it if it&#8217;s no longer needed. There are now 3 places where this is the case: successful loading, error and canceling.</p>
<p>This also shows how you can check the MIME type of the received data, because you might want to cancel the operation if it is not an image you are getting back.</p>
<p>I found that I needed to combine this approach with running the NSURLConnection on a background thread because otherwise there would be unwanted side effects impacting the tracking in my UIScrollView. As I mentioned before, I&#8217;m on shaky territory as I have never messed with run loops before. So please tell me if there&#8217;s some problem with this approach.</p>
<p>&#8230; and so Nyxouf did, his suggestion in the comments allowed me to remove quite a few lines of this nasty code after I found this to be working just as well. The trick seems to be to not have the connection start right away, but first schedule it on the current run loop for the common modes and then start it.</p>
<p><strong>DTLazyImageView.m</strong></p>

<div class="wp_codebox"><table><tr id="p5073130"><td class="code" id="p5073code130"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;DTLazyImageView.h&quot;</span>
&nbsp;
&nbsp;
<span style="color: #a61390;">@implementation</span> DTLazyImageView
&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>
	self.image <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
	<span style="color: #002200;">&#91;</span>_url release<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>_receivedData release<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>_connection cancel<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>_connection release<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>super dealloc<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>loadImageAtURL<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</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><span style="color: #002200;">&#41;</span>url
<span style="color: #002200;">&#123;</span>
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/"><span style="color: #400080;">NSURLRequest</span></a> <span style="color: #002200;">*</span>request <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/NSURLRequest_Class/"><span style="color: #400080;">NSURLRequest</span></a> alloc<span style="color: #002200;">&#93;</span> initWithURL<span style="color: #002200;">:</span>url 
			cachePolicy<span style="color: #002200;">:</span>NSURLRequestReturnCacheDataElseLoad timeoutInterval<span style="color: #002200;">:</span><span style="color: #2400d9;">10.0</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	_connection <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/NSURLConnection_Class/"><span style="color: #400080;">NSURLConnection</span></a> alloc<span style="color: #002200;">&#93;</span> initWithRequest<span style="color: #002200;">:</span>request delegate<span style="color: #002200;">:</span>self 
			startImmediately<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>_connection scheduleInRunLoop<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/"><span style="color: #400080;">NSRunLoop</span></a> currentRunLoop<span style="color: #002200;">&#93;</span> 
			forMode<span style="color: #002200;">:</span>NSRunLoopCommonModes<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>_connection start<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>request release<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>didMoveToSuperview
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>self.image <span style="color: #002200;">&amp;&amp;</span> _url <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">!</span>_connection<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>self loadImageAtURL<span style="color: #002200;">:</span>_url<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>cancelLoading
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>_connection cancel<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>_connection release<span style="color: #002200;">&#93;</span>, _connection <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>_receivedData release<span style="color: #002200;">&#93;</span>, _receivedData <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#pragma mark NSURL Loading</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>connection<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/"><span style="color: #400080;">NSURLConnection</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>connection didReceiveResponse<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLResponse_Class/"><span style="color: #400080;">NSURLResponse</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>response
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// every time we get an response it might be a forward, so we discard what data we have</span>
	<span style="color: #002200;">&#91;</span>_receivedData release<span style="color: #002200;">&#93;</span>, _receivedData <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// does not fire for local file URLs</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>response isKindOfClass<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPURLResponse_Class/"><span style="color: #400080;">NSHTTPURLResponse</span></a> class<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<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>httpResponse <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>response;
&nbsp;
		<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>httpResponse MIMEType<span style="color: #002200;">&#93;</span> hasPrefix<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
		<span style="color: #002200;">&#123;</span>
			<span style="color: #002200;">&#91;</span>self cancelLoading<span style="color: #002200;">&#93;</span>;
		<span style="color: #002200;">&#125;</span>
	<span style="color: #002200;">&#125;</span>
&nbsp;
	_receivedData <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>;
<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>connection<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/"><span style="color: #400080;">NSURLConnection</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>connection didReceiveData<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
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>_receivedData appendData<span style="color: #002200;">:</span>data<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>connectionDidFinishLoading<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/"><span style="color: #400080;">NSURLConnection</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>connection
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>_receivedData<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		UIImage <span style="color: #002200;">*</span>image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIImage alloc<span style="color: #002200;">&#93;</span> initWithData<span style="color: #002200;">:</span>_receivedData<span style="color: #002200;">&#93;</span>;
&nbsp;
		self.image <span style="color: #002200;">=</span> image;
&nbsp;
		<span style="color: #002200;">&#91;</span>image release<span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #002200;">&#91;</span>_receivedData release<span style="color: #002200;">&#93;</span>, _receivedData <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #002200;">&#91;</span>_connection release<span style="color: #002200;">&#93;</span>, _connection <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>connection<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/"><span style="color: #400080;">NSURLConnection</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>connection didFailWithError<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>error
<span style="color: #002200;">&#123;</span>
	NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Failed to load image at %@, %@&quot;</span>, _url, <span style="color: #002200;">&#91;</span>error localizedDescription<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>_connection release<span style="color: #002200;">&#93;</span>, _connection <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
	<span style="color: #002200;">&#91;</span>_receivedData release<span style="color: #002200;">&#93;</span>, _receivedData <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #6e371a;">#pragma mark Properties</span>
&nbsp;
<span style="color: #a61390;">@synthesize</span> url <span style="color: #002200;">=</span> _url;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5073&amp;md5=1b1ac9e727eaa8625d441d337e92e376" 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/05/and-now-lazy-loading-with-nsurlconnection/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5073&amp;md5=1b1ac9e727eaa8625d441d337e92e376" type="text/html" />"
	</item>
		<item>
		<title>A Quick Lazy-Loading UIImageView</title>
		<link>http://www.cocoanetics.com/2011/05/a-quick-lazy-loading-uiimageview/</link>
		<comments>http://www.cocoanetics.com/2011/05/a-quick-lazy-loading-uiimageview/#comments</comments>
		<pubDate>Fri, 20 May 2011 20:09:26 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5069</guid>
		<description><![CDATA[In case you ever need to enhance UIImageView to load it&#8217;s image lazily&#8230; like if it&#8217;s coming from a web URL. I used this on my NSAttributedStrings+HTML open source project to improve performance and also be able to have images that are not available locally. But you don&#8217;t want to do a synchronous call over the web, that would block your UI. I admit, it&#8217;s a quickie, but hey, sometimes those are also fun! Label Buy an ad here Readability DTLazyImageView.h @interface DTLazyImageView : UIImageView &#123; NSURL *_url; &#160; BOOL _loading; &#125; &#160; @property &#40;nonatomic, retain&#41; NSURL *url; &#160; @end DTLazyImageView.m #import &#34;DTLazyImageView.h&#34; &#160; @implementation DTLazyImageView &#160; - &#40;void&#41;dealloc &#123; self.image = nil; &#91;_url release&#93;; &#160; &#91;super dealloc&#93;; &#125; &#160; - &#40;void&#41;loadImageAtURL:&#40;NSURL *&#41;url &#123; NSAutoreleasePool *pool = &#91;&#91;NSAutoreleasePool alloc&#93; init&#93;; &#160; NSData *data = &#91;&#91;NSData alloc&#93; initWithContentsOfURL:url&#93;; &#160; if &#40;data&#41; &#123; UIImage *image = &#91;&#91;UIImage alloc&#93; initWithData:data&#93;; &#160; &#91;self performSelectorOnMainThread:@selector&#40;setImage:&#41; withObject:image waitUntilDone:YES&#93;; &#160; &#91;image release&#93;; &#125; &#160; &#91;data release&#93;; &#160; _loading = NO; &#160; &#91;pool release&#93;; &#125; &#160; - &#40;void&#41;didMoveToSuperview &#123; if &#40;!self.image &#38;&#38; _url &#38;&#38; !_loading&#41; &#123; _loading = YES; &#91;self performSelectorInBackground:@selector&#40;loadImageAtURL:&#41; withObject:_url&#93;; &#125; &#125; &#160; #pragma mark Properties &#160; @synthesize url = _url; &#160; @end You can see, it&#8217;s very simple. When the view is added to a super view by means of addSubview then it starts loading the image on a background thread. Setting the image has to occur on the main thread because UIKit is not threadsafe, or at least has not been until recently.]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/05/a-quick-lazy-loading-uiimageview/"></g:plusone></div><p>In case you ever need to enhance UIImageView to load it&#8217;s image lazily&#8230; like if it&#8217;s coming from a web URL.</p>
<p>I used this on my NSAttributedStrings+HTML open source project to improve performance and also be able to have images that are not available locally. But you don&#8217;t want to do a synchronous call over the web, that would block your UI.</p>
<p>I admit, it&#8217;s a quickie, but hey, sometimes those are also fun!</p>
<p><span id="more-5069"></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p><strong>DTLazyImageView.h</strong></p>

<div class="wp_codebox"><table><tr id="p5069133"><td class="code" id="p5069code133"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> DTLazyImageView <span style="color: #002200;">:</span> UIImageView 
<span style="color: #002200;">&#123;</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>_url;
&nbsp;
	<span style="color: #a61390;">BOOL</span> _loading;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</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>url;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p><strong>DTLazyImageView.m</strong></p>

<div class="wp_codebox"><table><tr id="p5069134"><td class="code" id="p5069code134"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;DTLazyImageView.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> DTLazyImageView
&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>
	self.image <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
	<span style="color: #002200;">&#91;</span>_url release<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>super dealloc<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>loadImageAtURL<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</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><span style="color: #002200;">&#41;</span>url
<span style="color: #002200;">&#123;</span>
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/"><span style="color: #400080;">NSAutoreleasePool</span></a> <span style="color: #002200;">*</span>pool <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/NSAutoreleasePool_Class/"><span style="color: #400080;">NSAutoreleasePool</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
&nbsp;
	<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><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> alloc<span style="color: #002200;">&#93;</span> initWithContentsOfURL<span style="color: #002200;">:</span>url<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>data<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		UIImage <span style="color: #002200;">*</span>image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIImage alloc<span style="color: #002200;">&#93;</span> initWithData<span style="color: #002200;">:</span>data<span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #002200;">&#91;</span>self performSelectorOnMainThread<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>setImage<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span> withObject<span style="color: #002200;">:</span>image 
				waitUntilDone<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #002200;">&#91;</span>image release<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #002200;">&#91;</span>data release<span style="color: #002200;">&#93;</span>;
&nbsp;
	_loading <span style="color: #002200;">=</span> <span style="color: #a61390;">NO</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>pool release<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>didMoveToSuperview
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>self.image <span style="color: #002200;">&amp;&amp;</span> _url <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">!</span>_loading<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		_loading <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;
		<span style="color: #002200;">&#91;</span>self performSelectorInBackground<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>loadImageAtURL<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span> withObject<span style="color: #002200;">:</span>_url<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>	
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#pragma mark Properties</span>
&nbsp;
<span style="color: #a61390;">@synthesize</span> url <span style="color: #002200;">=</span> _url;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>You can see, it&#8217;s very simple. When the view is added to a super view by means of addSubview then it starts loading the image on a background thread. Setting the image has to occur on the main thread because UIKit is not threadsafe, or at least has not been until recently.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5069&amp;md5=35d81fc3cc72ad3c39ff8db61e9950a1" 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/05/a-quick-lazy-loading-uiimageview/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5069&amp;md5=35d81fc3cc72ad3c39ff8db61e9950a1" type="text/html" />"
	</item>
		<item>
		<title>Functions as Parameters &#8211; Old &amp; New</title>
		<link>http://www.cocoanetics.com/2011/05/functions-as-parameters-old-new/</link>
		<comments>http://www.cocoanetics.com/2011/05/functions-as-parameters-old-new/#comments</comments>
		<pubDate>Thu, 19 May 2011 13:04:00 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5055</guid>
		<description><![CDATA[This topic is not for the faint of heart because it requires that you permit an additional level of abstraction in your brain to be able to grasp it. Until know all my ivars and properties where either scalar values (like an NSInteger) or pointers to Objective-C instances (like NSString *). But there are cases when you actually want to be able to store more complex functionality yet not have the overhead of object creation and messaging. From the C days we have a mechanism called &#8220;function pointers&#8221; and today I&#8217;ll show you how you can pass a function itself to an Obj-C class and store it in an instance variable. There are a couple of SDK functions that make use of that. The we&#8217;ll explore the modern-day equivalent of providing this sort of &#8220;plug in&#8221; dynamic functionality: doing the same thing with blocks. If you&#8217;re lucky to have iOS 4.x as minimum requirement for your project then those blocks might be nicer to work with than function pointers. Label Buy an ad here Readability We assume that we have a class MyClass where another developer should be able to provide a custom function to calculate or perform something on data that you send via parameters. Old: Function Pointers Let&#8217;s say we want to pass an integer and the custom C-function would return double of the input. float timesTwo&#40;int x&#41; &#123; return x * 2.0; &#125; To make it easier on us, let&#8217;s define a type for a pointer to such a function. You can also do without that, but then you&#8217;ll have to write many more round brackets and asterisks. A simple typedef saves us lots of work and possible errors. typedef float&#40;*customFunc&#41;&#40;int&#41;; I know this looks really weird and wrong, but trust me, that&#8217;s how you define a type customFunc that points to a function taking an int and returning a float. Note that this is a C-function, not an Objective-C instance method. Next let me show you a custom class that has a property of this type, one method to make use of that and another where you directly pass in your function. // .h typedef float&#40;*customFunc&#41;&#40;int&#41;; &#160; @interface MyClass : NSObject &#123; customFunc func; // ivar for function pointer &#125; &#160; @property &#40;nonatomic, assign&#41; customFunc func; &#160; - &#40;void&#41;useFunctionFrom:&#40;NSInteger&#41;from until:&#40;NSInteger&#41;until; - &#40;void&#41;doFunction:&#40;customFunc&#41;function; &#160; @end &#160; // .m &#160; @implementation MyClass &#160; - &#40;void&#41;useFunctionFrom:&#40;NSInteger&#41;from until:&#40;NSInteger&#41;until &#123; // if func is NULL then calling it crashes NSAssert&#40;func, @&#34;Function needs to be set!&#34;&#41;; &#160; for &#40;NSInteger i=from; i&#60;=until; i++&#41; &#123; float result = self.func&#40;i&#41;; NSLog&#40;@&#34;f(%d) = %.2f&#34;, i, result&#41;; &#125; &#125; &#160; - &#40;void&#41;doFunction:&#40;customFunc&#41;function &#123; for &#40;NSInteger i=1; i&#60;=5; i++&#41; &#123; float result = function&#40;i&#41;; NSLog&#40;@&#34;f(%d) = %.2f&#34;, i, result&#41;; &#125; &#125; &#160; @synthesize func; &#160; @end You use the customFunc type just like you would use any other variable type. But you need to make sure that it is not NULL because calling a null function pointer raises an exception. That&#8217;s what the NSAssert is for. In the first method we get the function from the synthesized getter (could also use the ivar directly) and call it, passing in i and logging the result. In the second method we call the passed function directly. It&#8217;s more clear if you consider this example: MyClass *m = &#91;&#91;MyClass alloc&#93; init&#93;; &#160; m.func = timesTwo; &#91;m useFunctionFrom:1 until:4&#93;; &#160; &#91;m doFunction:timesTwo&#93;; &#160; &#91;m release&#93;; In the first example we pass timesTwo which is literally a pointer to the function in memory that we created above. In the second example we do the same, but directly pass the function pointer instead of parking it in an instance variable. Now, this might sound very esoteric to you, but as I said there are certain use cases where it made sense to have your code call a custom function as opposed to just setting a multitude of parameters. For example NSArray has a method sortedArrayUsingFunction:context: - &#40;NSArray *&#41;sortedArrayUsingFunction:&#40;NSInteger &#40;*&#41;&#40;id, id, void *&#41;&#41;comparator context:&#40;void *&#41;context This weird stuff around the (*) we had typedef&#8217;ed away, I wonder why Apple didn&#8217;t&#8230; one function that you might use for this is shown in the documentation: NSInteger intSort&#40;id num1, id num2, void *context&#41; &#123; int v1 = &#91;num1 intValue&#93;; int v2 = &#91;num2 intValue&#93;; if &#40;v1 &#60; v2&#41; return NSOrderedAscending; else if &#40;v1 &#62; v2&#41; return NSOrderedDescending; else return NSOrderedSame; &#125; You see: two id pointers and a generic context and the return value provides the sort order of the two objects. Without the typedef the function parameter would have looked similar: &#8211; (void)doFunction:(float (*)(int))function New: Blocks We don&#8217;t want to stick forever with the old ways if something better is available and broadly supported. Blocks are such a new technology, available as of iOS 4.0 and most of the user devices are now running this version or [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/05/functions-as-parameters-old-new/"></g:plusone></div><p>This topic is not for the faint of heart because it requires that you permit an additional level of abstraction in your brain to be able to grasp it. Until know all my ivars and properties where either scalar values (like an NSInteger) or pointers to Objective-C instances (like NSString *). But there are cases when you actually want to be able to store more complex functionality yet not have the overhead of object creation and messaging.</p>
<p>From the C days we have a mechanism called &#8220;function pointers&#8221; and today I&#8217;ll show you how you can pass a function itself to an Obj-C class and store it in an instance variable. There are a couple of SDK functions that make use of that.</p>
<p>The we&#8217;ll explore the modern-day equivalent of providing this sort of &#8220;plug in&#8221; dynamic functionality: doing the same thing with blocks. If you&#8217;re lucky to have iOS 4.x as minimum requirement for your project then those blocks might be nicer to work with than function pointers.</p>
<p><span id="more-5055"></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>We assume that we have a class MyClass where another developer should be able to provide a custom function to calculate or perform something on data that you send via parameters.</p>
<h3>Old: Function Pointers</h3>
<p>Let&#8217;s say we want to pass an integer and the custom C-function would return double of the input.</p>

<div class="wp_codebox"><table><tr id="p5055145"><td class="code" id="p5055code145"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">float</span> timesTwo<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> x<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">return</span> x <span style="color: #339933;">*</span> <span style="color:#800080;">2.0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>To make it easier on us, let&#8217;s define a type for a pointer to such a function. You can also do without that, but then you&#8217;ll have to write many more round brackets and asterisks. A simple typedef saves us lots of work and possible errors.</p>

<div class="wp_codebox"><table><tr id="p5055146"><td class="code" id="p5055code146"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">typedef</span> <span style="color: #993333;">float</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>customFunc<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>I know this looks really weird and wrong, but trust me, that&#8217;s how you define a type customFunc that points to a function taking an int and returning a float. Note that this is a C-function, not an Objective-C instance method.</p>
<p>Next let me show you a custom class that has a property of this type, one method to make use of that and another where you directly pass in your function.</p>

<div class="wp_codebox"><table><tr id="p5055147"><td class="code" id="p5055code147"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// .h</span>
<span style="color: #a61390;">typedef</span> <span style="color: #a61390;">float</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">*</span>customFunc<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #a61390;">@interface</span> MyClass <span style="color: #002200;">:</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;">&#123;</span>
	customFunc func;  <span style="color: #11740a; font-style: italic;">// ivar for function pointer</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, assign<span style="color: #002200;">&#41;</span> customFunc func;   
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>useFunctionFrom<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span>from until<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span>until;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>doFunction<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>customFunc<span style="color: #002200;">&#41;</span>function;
&nbsp;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// .m</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> MyClass
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>useFunctionFrom<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span>from until<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span>until
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// if func is NULL then calling it crashes</span>
	NSAssert<span style="color: #002200;">&#40;</span>func, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Function needs to be set!&quot;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span>NSInteger i<span style="color: #002200;">=</span>from; i&lt;<span style="color: #002200;">=</span>until; i<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">float</span> result <span style="color: #002200;">=</span> self.func<span style="color: #002200;">&#40;</span>i<span style="color: #002200;">&#41;</span>;
		NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;f(%d) = %.2f&quot;</span>, i, result<span style="color: #002200;">&#41;</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>doFunction<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>customFunc<span style="color: #002200;">&#41;</span>function
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span>NSInteger i<span style="color: #002200;">=</span><span style="color: #2400d9;">1</span>; i&lt;<span style="color: #002200;">=</span><span style="color: #2400d9;">5</span>; i<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">float</span> result <span style="color: #002200;">=</span> function<span style="color: #002200;">&#40;</span>i<span style="color: #002200;">&#41;</span>;
		NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;f(%d) = %.2f&quot;</span>, i, result<span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@synthesize</span> func;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>You use the customFunc type just like you would use any other variable type. But you need to make sure that it is not NULL because calling a null function pointer raises an exception. That&#8217;s what the NSAssert is for.</p>
<p>In the first method we get the function from the synthesized getter (could also use the ivar directly) and call it, passing in i and logging the result. In the second method we call the passed function directly.</p>
<p>It&#8217;s more clear if you consider this example:</p>

<div class="wp_codebox"><table><tr id="p5055148"><td class="code" id="p5055code148"><pre class="objc" style="font-family:monospace;">MyClass <span style="color: #002200;">*</span>m <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>MyClass alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
&nbsp;
m.func <span style="color: #002200;">=</span> timesTwo;
<span style="color: #002200;">&#91;</span>m useFunctionFrom<span style="color: #002200;">:</span><span style="color: #2400d9;">1</span> until<span style="color: #002200;">:</span><span style="color: #2400d9;">4</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>m doFunction<span style="color: #002200;">:</span>timesTwo<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>m release<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>In the first example we pass timesTwo which is literally a pointer to the function in memory that we created above. In the second example we do the same, but directly pass the function pointer instead of parking it in an instance variable.</p>
<p>Now, this might sound very esoteric to you, but as I said there are certain use cases where it made sense to have your code call a custom function as opposed to just setting a multitude of parameters. For example NSArray has a method sortedArrayUsingFunction:context:</p>

<div class="wp_codebox"><table><tr id="p5055149"><td class="code" id="p5055code149"><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/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>sortedArrayUsingFunction<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSInteger <span style="color: #002200;">&#40;</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span>, <span style="color: #a61390;">id</span>, <span style="color: #a61390;">void</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>comparator 
       context<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>context</pre></td></tr></table></div>

<p>This weird stuff around the (*) we had typedef&#8217;ed away, I wonder why Apple didn&#8217;t&#8230; one function that you might use for this is shown in the documentation:</p>

<div class="wp_codebox"><table><tr id="p5055150"><td class="code" id="p5055code150"><pre class="objc" style="font-family:monospace;">NSInteger intSort<span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span> num1, <span style="color: #a61390;">id</span> num2, <span style="color: #a61390;">void</span> <span style="color: #002200;">*</span>context<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">int</span> v1 <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>num1 intValue<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">int</span> v2 <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>num2 intValue<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>v1 &lt; v2<span style="color: #002200;">&#41;</span>        
     <span style="color: #a61390;">return</span> NSOrderedAscending;
        <span style="color: #a61390;">else</span> <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>v1 &gt; v2<span style="color: #002200;">&#41;</span>
    <span style="color: #a61390;">return</span> NSOrderedDescending;
        <span style="color: #a61390;">else</span>
    <span style="color: #a61390;">return</span> NSOrderedSame;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>You see: two id pointers and a generic context and the return value provides the sort order of the two objects. Without the typedef the function parameter would have looked similar: &#8211; (void)doFunction:(float (*)(int))function</p>
<h3>New: Blocks</h3>
<p>We don&#8217;t want to stick forever with the old ways if something better is available and broadly supported. Blocks are such a new technology, available as of iOS 4.0 and most of the user devices are now running this version or higher. So for new projects we can look at the new and shiny stuff.</p>
<p>Blocks are similar in function to function points, but you can put all your code inline and together with the code also all local variables are preserved. At least, that&#8217;s how I understand it, honestly I&#8217;m just beginning with blocks myself. The Pragmatic Studio did this <a href="http://pragmaticstudio.com/blog/2010/7/28/ios4-blocks-1">great introduction to blocks</a>.</p>
<p>We find that when changing MyClass from using a function pointer to using block variables the only relevant change we need to make is replace an * for a ^.</p>

<div class="wp_codebox"><table><tr id="p5055151"><td class="code" id="p5055code151"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// .h</span>
&nbsp;
<span style="color: #a61390;">typedef</span> <span style="color: #a61390;">float</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span>customBlock<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #a61390;">@interface</span> MyClass <span style="color: #002200;">:</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;">&#123;</span>
	customBlock blk; <span style="color: #11740a; font-style: italic;">// ivar for block</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, copy<span style="color: #002200;">&#41;</span> customBlock blk;  
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>useBlockFrom<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span>from until<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span>until;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>doBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>customBlock<span style="color: #002200;">&#41;</span>block;
&nbsp;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// .m</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> MyClass
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>dealloc
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>blk release<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>useBlockFrom<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span>from until<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>NSInteger<span style="color: #002200;">&#41;</span>until
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// if func is NULL then calling it crashes</span>
	NSAssert<span style="color: #002200;">&#40;</span>blk, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Block needs to be set!&quot;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span>NSInteger i<span style="color: #002200;">=</span>from; i&lt;<span style="color: #002200;">=</span>until; i<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">float</span> result <span style="color: #002200;">=</span> self.blk<span style="color: #002200;">&#40;</span>i<span style="color: #002200;">&#41;</span>;
		NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;f(%d) = %.2f&quot;</span>, i, result<span style="color: #002200;">&#41;</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>doBlock<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>customBlock<span style="color: #002200;">&#41;</span>block
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span>NSInteger i<span style="color: #002200;">=</span><span style="color: #2400d9;">1</span>; i&lt;<span style="color: #002200;">=</span><span style="color: #2400d9;">5</span>; i<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">float</span> result <span style="color: #002200;">=</span> block<span style="color: #002200;">&#40;</span>i<span style="color: #002200;">&#41;</span>;
		NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;f(%d) = %.2f&quot;</span>, i, result<span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@synthesize</span> blk;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>It&#8217;s on the calling end that most of the changes are.</p>
<p>EDIT: Turns out that for a block property you need to use copy instead of assign, this will copy the block to the heap where it will continue to live. Blocks are treated like object and so you also need to release copy properties.</p>

<div class="wp_codebox"><table><tr id="p5055152"><td class="code" id="p5055code152"><pre class="objc" style="font-family:monospace;">MyClass <span style="color: #002200;">*</span>m <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>MyClass alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// inline</span>
m.blk <span style="color: #002200;">=</span> <span style="color: #002200;">^</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> x<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span> <span style="color: #a61390;">return</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">float</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span>x <span style="color: #002200;">*</span> <span style="color: #2400d9;">2.0</span><span style="color: #002200;">&#41;</span>; <span style="color: #002200;">&#125;</span>;
<span style="color: #002200;">&#91;</span>m useBlockFrom<span style="color: #002200;">:</span><span style="color: #2400d9;">1</span> until<span style="color: #002200;">:</span><span style="color: #2400d9;">4</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// block variable</span>
<span style="color: #a61390;">float</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">^</span>blockTimesTwo<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">=</span> <span style="color: #002200;">^</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> x<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">return</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">float</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span>x <span style="color: #002200;">*</span> <span style="color: #2400d9;">2.0</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>m doBlock<span style="color: #002200;">:</span>blockTimesTwo<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>m release<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>One thing that stumped me at first was that you have to make sure that the value you return from inside the block has to have matching datatypes with the block prototype. Without the specific typecast (float)(&#8230;) the result is a double and causes the compiler to complain about that.</p>
<p>The first use has the code to be put into the block property inline. The second use creates a block variable first and then passes this into the second method. This is just to show how it looks without using our special type. It works just the same using that and might be way easier to read:</p>

<div class="wp_codebox"><table><tr id="p5055153"><td class="code" id="p5055code153"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// block variable</span>
customBlock blockTimesTwo <span style="color: #002200;">=</span> <span style="color: #002200;">^</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> x<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">return</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">float</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span>x <span style="color: #002200;">*</span> <span style="color: #2400d9;">2.0</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>;</pre></td></tr></table></div>

<p>So far we have exactly the same functionality as with function pointers, but now for the grande finale we&#8217;ll find why pros all around prefer blocks nowadays. Can you spot it?</p>

<div class="wp_codebox"><table><tr id="p5055154"><td class="code" id="p5055code154"><pre class="objc" style="font-family:monospace;">MyClass <span style="color: #002200;">*</span>m <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>MyClass alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #a61390;">float</span> mul <span style="color: #002200;">=</span> <span style="color: #2400d9;">3.0</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// block variable</span>
customBlock blockTimesAnything <span style="color: #002200;">=</span> <span style="color: #002200;">^</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> x<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">return</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">float</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span>x <span style="color: #002200;">*</span> mul<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>;
&nbsp;
mul <span style="color: #002200;">=</span> <span style="color: #2400d9;">10.0</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>m doBlock<span style="color: #002200;">:</span>blockTimesAnything<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>m release<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>You see that within the {} of the block we still have access to the local variable mul. Furthermore the block sort of takes a snapshot of the variable at the time when it is defined. Setting mul to 10 afterwards has no effect, it&#8217;s still using 3. So besides of having the new variables available that you define in the as block parameters, you also get snapshots of local variables.</p>
<p>The typedef trick I have shown in this article greatly simplifies the code. One of the reasons why you generally don&#8217;t see this in the wild is that Apple seems to prefer to have the entire type definition in the block parameters so that you don&#8217;t have to look up what parameters the block has. It is really up to you whether or not you want this simplification at the cost of a bit of in-transparency. An onlooker would have to go into your header to find what the block parameters and return type should be.</p>
<h3>Conclusion</h3>
<p>The ability to access snapshots of local variables is what makes blocks orders of magnitude more useful if you want to enable other developers to provide &#8220;plug-in&#8221; custom functionality to your classes. The other guys can chose whatever ingredients they like at the time of setting the block and are no longer limited to using only the passed parameters or &#8211; in case of delegate methods &#8211; some ivars.</p>
<p>So if you have a choice then you might want to convert your function pointer properties into block properties, doing so might only require that you change a * to a ^. For this little tweak you open up a new world of customization possibilities for the happy developers who get to use your code.</p>
<p>It&#8217;s exactly these benefits why Apple has begun switching to blocks wherever they can, in most cases new methods where added (with blocks as parameters) that can achieve things where previously you had to painstakingly message back and forth.</p>
<p>We say: good idea!</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5055&amp;md5=2e9b933b2ca4d76b20ed74631d34eebf" 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/05/functions-as-parameters-old-new/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5055&amp;md5=2e9b933b2ca4d76b20ed74631d34eebf" type="text/html" />"
	</item>
		<item>
		<title>Mutability Preserverance</title>
		<link>http://www.cocoanetics.com/2011/05/mutability-preserverance/</link>
		<comments>http://www.cocoanetics.com/2011/05/mutability-preserverance/#comments</comments>
		<pubDate>Fri, 06 May 2011 07:33:10 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=4972</guid>
		<description><![CDATA[Apple consciously separates mutable and immutable variants of classes in Objective-C. If you have an NSString you cannot modify it, only by creating a new one with additions to an old one. If you want to mutilate mutate the string itself you have to use it&#8217;s subclass NSMutableString. Internally those are the same CoreFoundation type, yet the design choice was to have an immutable class and add mutability methods in a subclass. There are two items that are not immediately obvious if you start out learning to program Objective-C, that I&#8217;d like to chronicle. One of these stumped me just a few days ago. Label Buy an ad here Readability Take for example the two methods to manipulate a string. NSString *text = @&#34;Constant String&#34;; text = &#91;text stringByAppendingString:@&#34;, really constant?&#34;&#93;; NSLog&#40;@&#34;%@&#34;, text&#41;; You see that you can reuse the text variable and don&#8217;t have to create a new NSString pointer. This works because the first string is statically allocated by the compiler as part of the compiled code. The @&#8221;" is the shorthand for that. We have to assign the return value of stringByAppendingString to the pointer variable because this is a new NSString instance, marked as autoreleased. How long do these strings live? The constant one stays around until the app gets unloaded from memory, i.e. when it is terminated. Though if you don&#8217;t hold onto the pointer to the static allocation then this amounts to a leak, the memory stays lost but you have no way to access it any more. But there&#8217;s nothing you can do about that. The autoreleased new string object will live until the next run loop, which is probably at the end of the method inside which you have place the code. The mutable alternative: NSMutableString *text = &#91;NSMutableString stringWithString:@&#34;Constant String&#34;&#93;; &#91;text appendString:@&#34;, really constant?&#34;&#93;; NSLog&#40;@&#34;%@&#34;, text&#41;; You see that appendString does not return a value because we don&#8217;t create a new object. Instead text itself is mutated. You still see the @&#8221;" because there is no shorthand to create an NSMutableString. So we still end up with &#8220;Constant String&#8221; statically allocated in memory and a new NSMutableString instance. But in this case this new instance is already created in the first line through the stringWithString. The following appendString does not create a new instance but mutates text. What would the difference be if you had also declared text as NSString * in the second example? Not much, you would get a compiler warning that NSString might not have a appendString method because the compiler goes by the declaration. At runtime it&#8217;s still a pointer to an NSMutableString that ends up written into the variable, so messaging that with appendString works without problem. Also, since NSMutableString is a subclass of NSString you can use it anywhere you would need an NSString parameter, the additional mutability methods are irrelevant and will be ignored. So much for a quick reminder about mutability basics. Besides of using these methods that create autoreleased new instances you can also copy objects. This is the first thing that somebody needs to tell you because it is counterintuitive. What does the following code produce? NSMutableString *text = &#91;NSMutableString stringWithString:@&#34;Constant Text&#34;&#93;; id newText = &#91;text copy&#93;; You might assume that newText is now a mutable copy of text, but that would be wrong. copy always makes immutable copies, even if the original was mutable. To make a mutable copy use the mutableCopy method. [NSString copy] = NSString [NSMutableString copy] = NSString [NSString mutableCopy] = NSMutableString [NSMutableString mutableCopy] = NSMutableString Anything with init, new or copy in the method name will not be autoreleased. So you have to make sure that you release it before you leave the current scope or else this will produce a leak, this time a preventable one. When I started out to program Objective-C I made all synthesized properties on classes retain. But then you find &#8211; when looking at the documentation or Apple&#8217;s headers &#8211; that often properties are not retain, but copy instead. The reason being that a retained property is just a reference to an instance created earlier. If it&#8217;s an NSMutableString you pass into a method expecting an NSString that works nicely, but you can still mutate the string outside of the class. Which might lead to unexpected results. Because of this any property there you want the &#8220;value&#8221; at this present time to be passed, you should make a copy instead. This copy is a snapshot at the time when the property was used to set the instance variable and no unexpected effects happen if you mutate the parameter afterwards. If you want a reference to the original and know for certain that you also will want to have access to subsequent updates of the passed instance, then retain will be [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/05/mutability-preserverance/"></g:plusone></div><p>Apple consciously separates mutable and immutable variants of classes in Objective-C. If you have an NSString you cannot modify it, only by creating a new one with additions to an old one. If you want to <del>mutilate</del> mutate the string itself you have to use it&#8217;s subclass NSMutableString. Internally those are the same CoreFoundation type, yet the design choice was to have an immutable class and add mutability methods in a subclass.</p>
<p>There are two items that are not immediately obvious if you start out learning to program Objective-C, that I&#8217;d like to chronicle. One of these stumped me just a few days ago.</p>
<p><span id="more-4972"></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>Take for example the two methods to manipulate a string.</p>

<div class="wp_codebox"><table><tr id="p4972161"><td class="code" id="p4972code161"><pre class="objc" style="font-family:monospace;"><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>text <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Constant String&quot;</span>;
text <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>text stringByAppendingString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;, really constant?&quot;</span><span style="color: #002200;">&#93;</span>;
NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>, text<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>You see that you can reuse the text variable and don&#8217;t have to create a new NSString pointer. This works because the first string is statically allocated by the compiler as part of the compiled code. The @&#8221;" is the shorthand for that. We have to assign the return value of stringByAppendingString to the pointer variable because this is a new NSString instance, marked as autoreleased.</p>
<p>How long do these strings live? The constant one stays around until the app gets unloaded from memory, i.e. when it is terminated. Though if you don&#8217;t hold onto the pointer to the static allocation then this amounts to a leak, the memory stays lost but you have no way to access it any more. But there&#8217;s nothing you can do about that. The autoreleased new string object will live until the next run loop, which is probably at the end of the method inside which you have place the code.</p>
<p>The mutable alternative:</p>

<div class="wp_codebox"><table><tr id="p4972162"><td class="code" id="p4972code162"><pre class="objc" style="font-family:monospace;"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableString_Class/"><span style="color: #400080;">NSMutableString</span></a> <span style="color: #002200;">*</span>text <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableString_Class/"><span style="color: #400080;">NSMutableString</span></a> stringWithString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Constant String&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>text appendString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;, really constant?&quot;</span><span style="color: #002200;">&#93;</span>;
NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>, text<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>You see that appendString does not return a value because we don&#8217;t create a new object. Instead text itself is mutated. You still see the @&#8221;" because there is no shorthand to create an NSMutableString. So we still end up with &#8220;Constant String&#8221; statically allocated in memory and a new NSMutableString instance. But in this case this new instance is already created in the first line through the stringWithString. The following appendString does not create a new instance but mutates text.</p>
<p>What would the difference be if you had also declared text as NSString * in the second example? Not much, you would get a compiler warning that NSString might not have a appendString method because the compiler goes by the declaration. At runtime it&#8217;s still a pointer to an NSMutableString that ends up written into the variable, so messaging that with appendString works without problem. Also, since NSMutableString is a subclass of NSString you can use it anywhere you would need an NSString parameter, the additional mutability methods are irrelevant and will be ignored.</p>
<p>So much for a quick reminder about mutability basics. Besides of using these methods that create autoreleased new instances you can also copy objects. This is the first thing that somebody needs to tell you because it is counterintuitive. What does the following code produce?</p>

<div class="wp_codebox"><table><tr id="p4972163"><td class="code" id="p4972code163"><pre class="objc" style="font-family:monospace;"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableString_Class/"><span style="color: #400080;">NSMutableString</span></a> <span style="color: #002200;">*</span>text <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableString_Class/"><span style="color: #400080;">NSMutableString</span></a> stringWithString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Constant Text&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #a61390;">id</span> newText <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>text copy<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>You might assume that newText is now a mutable copy of text, but that would be <em>wrong</em>. copy always makes immutable copies, even if the original was mutable. To make a mutable copy use the mutableCopy method.</p>
<p>[NSString copy] = NSString<br />
[NSMutableString copy] = NSString<br />
[NSString mutableCopy] = NSMutableString<br />
[NSMutableString mutableCopy] = NSMutableString</p>
<p>Anything with init, new or copy in the method name will not be autoreleased. So you have to make sure that you release it before you leave the current scope or else this will produce a leak, this time a preventable one.</p>
<p>When I started out to program Objective-C I made all synthesized properties on classes retain. But then you find &#8211; when looking at the documentation or Apple&#8217;s headers &#8211; that often properties are not retain, but copy instead. The reason being that a retained property is just a reference to an instance created earlier. If it&#8217;s an NSMutableString you pass into a method expecting an NSString that works nicely, but you can still mutate the string outside of the class. Which might lead to unexpected results.</p>
<p>Because of this any property there you want the &#8220;value&#8221; at this present time to be passed, you should make a copy instead. This copy is a snapshot at the time when the property was used to set the instance variable and no unexpected effects happen if you mutate the parameter afterwards. If you want a reference to the original and know for certain that you also will want to have access to subsequent updates of the passed instance, then retain will be your choice.</p>

<div class="wp_codebox"><table><tr id="p4972164"><td class="code" id="p4972code164"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> MyClass <span style="color: #002200;">:</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;">&#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>_name;
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/"><span style="color: #400080;">NSDateFormatter</span></a> <span style="color: #002200;">*</span>_birthdayDateFormatter;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, copy<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>name;
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/"><span style="color: #400080;">NSDateFormatter</span></a> <span style="color: #002200;">*</span>birthdayDateFormatter;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>Both would have a release in the dealloc method. Usually you would simply @synthesize the methods for the properties defined above. But let&#8217;s look at how those would be written manually. Since I don&#8217;t like to rename the parameter of an overwritten setter, I usually prefix my instance variables with _. So you can imagine a @synthesize name = _name, property name equals instance variable name.</p>
<p>In this example we want to have the value of the name passed and preserved in our MyClass. But the dateFormatter might get a different format or locale during the runtime of our app, so we only retain it and don&#8217;t make a copy. Bear in mind, that to be able to copy any object the NSCopying protocol needs to be implemented. This means you have to implement the copyWithZone: for your own classes to support copy method. For mutableCopy the method to implement is in the NSMutableCopying protocol, i.e. mutableCopyWithZone.</p>
<p>The case where I run into an unexpected error was when I had an NSMutableArray instance variable that I wanted to also copy to copies of this class. Those lost mutability and when I tried to add items later I got the usual unrecognizedSelector exception.</p>

<div class="wp_codebox"><table><tr id="p4972165"><td class="code" id="p4972code165"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;MyClass.h&quot;</span>
&nbsp;
<span style="color: #a61390;">@implementation</span> MyClass
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>dealloc
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>_name release<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>_birthdayDateFormatter release<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #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>setName<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>name
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>name <span style="color: #002200;">!=</span> _name<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>_name release<span style="color: #002200;">&#93;</span>;
		_name <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>name copy<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>setBirthdayDateFormatter<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/"><span style="color: #400080;">NSDateFormatter</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>birthdayDateFormatter
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>birthdayDateFormatter <span style="color: #002200;">!=</span> _birthdayDateFormatter<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>_birthdayDateFormatter release<span style="color: #002200;">&#93;</span>;
		_birthdayDateFormatter <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>birthdayDateFormatter retain<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@synthesize</span> name <span style="color: #002200;">=</span> _name;
<span style="color: #a61390;">@synthesize</span> birthdayDateFormatter <span style="color: #002200;">=</span> _birthdayDateFormatter;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>This is about the code that the @synthesize would create for you. The if serves to not release the ivar if it is the same because this might free the object. I&#8217;ve also seen some people ditch the if and instead use an autorelease, but that just feels wrong to me. Writing less code is not always a good thing.</p>
<p>You can see that the only difference here is that one uses a retain, the other a copy to preserve the object while it&#8217;s being used by MyClass. We still have the synthesizes because those create the getters for us, but these are the same for retain, copy and assign.</p>
<p>Now you know why mutability gets lost when you assign a mutable object to a copy property. Which was exactly what I did on the copyWithZone: implementation of <a href="https://github.com/Cocoanetics/NSAttributedString-Additions-for-HTML/commit/3cbf7be2e146a4ae98f8c1a41ee15950e8beb505">DTCoreTextParagraphStyle</a>.</p>

<div class="wp_codebox"><table><tr id="p4972166"><td class="code" id="p4972code166"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#pragma mark Copying</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>copyWithZone<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">NSZone</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>zone
<span style="color: #002200;">&#123;</span>
    DTCoreTextParagraphStyle <span style="color: #002200;">*</span>newObject <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>DTCoreTextParagraphStyle allocWithZone<span style="color: #002200;">:</span>zone<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
&nbsp;
    newObject.firstLineIndent <span style="color: #002200;">=</span> self.firstLineIndent;
    newObject.defaultTabInterval <span style="color: #002200;">=</span> self.defaultTabInterval;
    newObject.tabStops <span style="color: #002200;">=</span> self.tabStops; <span style="color: #11740a; font-style: italic;">// copy</span>
&nbsp;
    <span style="color: #a61390;">return</span> newObject;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>So I overwrite the setter to substitute mutableCopy for the copy. Granted this is a very rare case to do that, but there is no other way to transfer a copy to a new object and still preserve mutability. Theoretically I could have also made the instance mutable lazily just before adding something new to it, but the code to do that is way longer than this overwritten setter and harder to understand.</p>
<p>Other smarter people have also stumbled over this. May this article prevent you from ever losing mutability when you depend on it.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4972&amp;md5=a5e8961e4faecb6d18bbb2313bc16b7a" 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/05/mutability-preserverance/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4972&amp;md5=a5e8961e4faecb6d18bbb2313bc16b7a" type="text/html" />"
	</item>
		<item>
		<title>Visual View Debugging</title>
		<link>http://www.cocoanetics.com/2011/05/visual-view-debugging/</link>
		<comments>http://www.cocoanetics.com/2011/05/visual-view-debugging/#comments</comments>
		<pubDate>Sun, 01 May 2011 11:38:19 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=4959</guid>
		<description><![CDATA[In this article I want to summarize a couple of &#8220;barefoot techniques&#8221; for tuning your views. Sometimes you are painstakingly putting together a UI with multiple views and you cannot tell any more where one ends and another begins. The debugger is not really working well on this because most of the interesting information about views is hidden behind properties and you cannot usefully inspect their current contents because properties are really methods the value of which is only set when you actually call them. But I want to share some easy techniques that I started using so that I can get this visual puzzle untangled. Label Buy an ad here Readability There are two kinds of approaches to debugging the visuals of a UIView. You can either look at some textual description of it and see if the numbers match up with what you&#8217;re expecting. Or you can mark and highlight a view such that you can visually judge whether it is in the right place. Getting View Info As any NSObject subclass UIView also has a descriptive description. It will tell you the view&#8217;s frame, class, autoresizing mask so you don&#8217;t have to fuss to extract the view&#8217;s frame with NSStringFromCGRect but you can simply NSLog the view directly. NSLog&#40;@&#34;%@&#34;, view&#41;; Output from this contains the current frame, autoresizing mask and info about the backing layer. Note: on iOS all views are layer backed and you can choose your own layer class to be used for any view. But if you don&#8217;t then CALayer is used. &#60;UIView: 0x4b15960; frame = (0 20; 320 460); autoresize = W+H; layer = &#60;CALayer: 0x4b15a40&#62;&#62; This simple technique can also reveal if you might inadvertently positioned the origin of the view on a non-integer value. This typically causes text to look blurry due to the antialiasing that get&#8217;s applied there. Here&#8217;s an example from one of my recent projects, you&#8217;ll have to open up the image in full resulution to see the difference. Something like this might happen of you don&#8217;t set a view&#8217;s frame, but instead set it&#8217;s size via the bounds or center property. If the width or height are not dividable by 2 then you&#8217;ll get this affect, but you&#8217;ll only notice it when some perfectionist asks you why some label does not look as crisp as all the others. NSLogging a simple view goes a long way, but it cannot reveal the hierarchy of views. One might be tempted to write some recursive category extension to also show a view&#8217;s subviews. But actually this work has already been done for us, by Apple! UIView has a hidden (i.e. private) method named recursiveDescription which works just like description but recursively walks through a view&#8217;s children and their children and shows it in sort of a textual tree. You cannot have this in production code, but just for debugging all you need is to add a few lines to tell the compiler that this is a valid method. @interface UIView &#40;debug&#41; &#160; - &#40;NSString *&#41;recursiveDescription; &#160; @end Alternatively you can simply ignore the warning that the method might not exist. Output from this might look like: &#60;UIWindow: 0x4e31810; frame = (0 0; 320 480); opaque = NO; autoresize = RM+BM; layer = &#60;CALayer: 0x4e319a0&#62;&#62; &#124; &#60;UIView: 0x6015f60; frame = (0 20; 320 460); autoresize = W+H; layer = &#60;CALayer: 0&#215;6016040&#62;&#62; You see a pipe symbol that shows which superview a view belongs to. You also see that the individual views are just shown with their regular description.  See a view&#8217;s structure of children might tell you some interesting things about stock views that come with the SDK. For example you would see that UIScrollView has some small UIImageViews as children: those are the scroll indicators! Don&#8217;t forget to remove the NSLog statements you added just for debugging. You don&#8217;t have to remove all log statements for production code, but you can leave in log statements that give some interesting information. But if you leave in logs of view descriptions you deserve to be flogged. Seeing the Dimensions of the View If you have a view visible but are uncertain if all of it is showing then you can give it&#8217;s layer a distinct border color to visualize it. If you see the border all around and nothing is cut off then all is well. By linking in the QuartzCore.framework and adding the &#60;QuartzCore/QuartzCore.h&#62; at the top of your file you gain access the properties of the UIView&#8217;s backing layer. Without that you can only get as far as the view&#8217;s layer, but all the properties of the CALayer class are defined in this header. This allows you to set a border so you can see if your view is fully visible. This example sets it to red (note the use [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/05/visual-view-debugging/"></g:plusone></div><p>In this article I want to summarize a couple of &#8220;barefoot techniques&#8221; for tuning your views. Sometimes you are painstakingly putting together a UI with multiple views and you cannot tell any more where one ends and another begins.</p>
<p>The debugger is not really working well on this because most of the interesting information about views is hidden behind properties and you cannot usefully inspect their current contents because properties are really methods the value of which is only set when you actually call them.</p>
<p>But I want to share some easy techniques that I started using so that I can get this visual puzzle untangled.</p>
<p><span id="more-4959"></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>There are two kinds of approaches to debugging the visuals of a UIView. You can either look at some textual description of it and see if the numbers match up with what you&#8217;re expecting. Or you can mark and highlight a view such that you can visually judge whether it is in the right place.</p>
<h3>Getting View Info</h3>
<p>As any NSObject subclass UIView also has a descriptive <strong>description</strong>. It will tell you the view&#8217;s frame, class, autoresizing mask so you don&#8217;t have to fuss to extract the view&#8217;s frame with NSStringFromCGRect but you can simply NSLog the view directly.</p>

<div class="wp_codebox"><table><tr id="p4959171"><td class="code" id="p4959code171"><pre class="objc" style="font-family:monospace;">NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>, view<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>Output from this contains the current frame, autoresizing mask and info about the backing layer. Note: on iOS all views are layer backed and you can choose your own layer class to be used for any view. But if you don&#8217;t then CALayer is used.</p>
<p><strong>&lt;UIView: 0x4b15960; frame = (0 20; 320 460); autoresize = W+H; layer = &lt;CALayer: 0x4b15a40&gt;&gt;</strong></p>
<p>This simple technique can also reveal if you might inadvertently positioned the origin of the view on a non-integer value. This typically causes text to look blurry due to the antialiasing that get&#8217;s applied there. Here&#8217;s an example from one of my recent projects, you&#8217;ll have to open up the image in full resulution to see the difference.</p>
<p><a href="http://www.cocoanetics.com/files/blur.png"><img class="alignnone size-full wp-image-4963" title="Blurry image due to non-integer origin" src="http://www.cocoanetics.com/files/blur.png" alt="" width="779" height="545" /></a></p>
<p>Something like this might happen of you don&#8217;t set a view&#8217;s frame, but instead set it&#8217;s size via the bounds or center property. If the width or height are not dividable by 2 then you&#8217;ll get this affect, but you&#8217;ll only notice it when some perfectionist asks you why some label does not look as crisp as all the others.</p>
<p>NSLogging a simple view goes a long way, but it cannot reveal the hierarchy of views. One might be tempted to write some recursive category extension to also show a view&#8217;s subviews. But actually this work has already been done for us, by Apple!</p>
<p>UIView has a hidden (i.e. private) method named <strong>recursiveDescription</strong> which works just like description but recursively walks through a view&#8217;s children and their children and shows it in sort of a textual tree. You cannot have this in production code, but just for debugging all you need is to add a few lines to tell the compiler that this is a valid method.</p>

<div class="wp_codebox"><table><tr id="p4959172"><td class="code" id="p4959code172"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> UIView <span style="color: #002200;">&#40;</span>debug<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>recursiveDescription;
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>Alternatively you can simply ignore the warning that the method might not exist. Output from this might look like:</p>
<p><strong>&lt;UIWindow: 0x4e31810; frame = (0 0; 320 480); opaque = NO; autoresize = RM+BM; layer = &lt;CALayer: 0x4e319a0&gt;&gt;<br />
</strong><strong>| &lt;UIView: 0x6015f60; frame = (0 20; 320 460); autoresize = W+H; layer = &lt;CALayer: 0&#215;6016040&gt;&gt;</strong></p>
<p>You see a pipe symbol that shows which superview a view belongs to. You also see that the individual views are just shown with their regular description.  See a view&#8217;s structure of children might tell you some interesting things about stock views that come with the SDK. For example you would see that UIScrollView has some small UIImageViews as children: those are the scroll indicators!</p>
<p>Don&#8217;t forget to remove the NSLog statements you added just for debugging. You don&#8217;t have to remove all log statements for production code, but you can leave in log statements that give some interesting information. But if you leave in logs of view descriptions you deserve to be flogged.</p>
<h3>Seeing the Dimensions of the View</h3>
<p>If you have a view visible but are uncertain if all of it is showing then you can give it&#8217;s layer a <strong>distinct border color</strong> to visualize it. If you see the border all around and nothing is cut off then all is well.</p>
<p>By linking in the QuartzCore.framework and adding the &lt;QuartzCore/QuartzCore.h&gt; at the top of your file you gain access the properties of the UIView&#8217;s backing layer. Without that you can only get as far as the view&#8217;s layer, but all the properties of the CALayer class are defined in this header.</p>
<p>This allows you to set a border so you can see if your view is fully visible. This example sets it to red (note the use of CGColor instead of UIColor) and the border width to 1 so that it&#8217;s visible. I recently used this to see if a video preview layer is indeed showing fully.</p>

<div class="wp_codebox"><table><tr id="p4959173"><td class="code" id="p4959code173"><pre class="objc" style="font-family:monospace;">view.layer.borderColor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIColor redColor<span style="color: #002200;">&#93;</span>.CGColor;
view.layer.borderWidth <span style="color: #002200;">=</span> <span style="color: #2400d9;">1.0</span>;</pre></td></tr></table></div>

<p>Another technique that I love to use, especially when working with multi-page scrollviews is to have the child views and the parent views all with different background colors. Now you could just set the backgroundColor for all but I found that it gets boring after a while because you always think of the same primary colors. Red. Green. Blue. Yellow. Purple if you feel fancy. Wouldn&#8217;t it be much nicer if you saw a fresh random color every time you start the app again to see if the views line up?</p>
<p>A simple category on UIColor gives you a randomColor method so that you never run out of ideas for temporary background colors.</p>

<div class="wp_codebox"><table><tr id="p4959174"><td class="code" id="p4959code174"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// this in the header</span>
<span style="color: #a61390;">@interface</span> UIColor <span style="color: #002200;">&#40;</span>debug<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span>UIColor <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>randomColor;
<span style="color: #a61390;">@end</span>
&nbsp;
<span style="color: #11740a; font-style: italic;">// this in the implementation</span>
<span style="color: #a61390;">@implementation</span> UIColor <span style="color: #002200;">&#40;</span>debug<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span>UIColor <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>randomColor
<span style="color: #002200;">&#123;</span>
    CGFloat red <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>arc4random<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">%</span>256<span style="color: #002200;">&#41;</span><span style="color: #002200;">/</span><span style="color: #2400d9;">256.0</span>;
    CGFloat green <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>arc4random<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">%</span>256<span style="color: #002200;">&#41;</span><span style="color: #002200;">/</span><span style="color: #2400d9;">256.0</span>;
    CGFloat blue <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>arc4random<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">%</span>256<span style="color: #002200;">&#41;</span><span style="color: #002200;">/</span><span style="color: #2400d9;">256.0</span>;
&nbsp;
    <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>UIColor colorWithRed<span style="color: #002200;">:</span>red green<span style="color: #002200;">:</span>green blue<span style="color: #002200;">:</span>blue alpha<span style="color: #002200;">:</span><span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>Never again those boring primary colors!</p>
<h3>Conclusion</h3>
<p>These are the two methods of how to get useful descriptions of views as well as how to visually mark views so that you can be certain that they are in the right spot. If you know any others that are also fun, then please comment.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4959&amp;md5=9921fa8cee49ceb690bf04cad1858969" 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/05/visual-view-debugging/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4959&amp;md5=9921fa8cee49ceb690bf04cad1858969" type="text/html" />"
	</item>
		<item>
		<title>Splitting a String into Paragraphs &#8230; with Blocks</title>
		<link>http://www.cocoanetics.com/2011/04/splitting-a-string-into-paragraphs-with-blocks/</link>
		<comments>http://www.cocoanetics.com/2011/04/splitting-a-string-into-paragraphs-with-blocks/#comments</comments>
		<pubDate>Wed, 06 Apr 2011 17:42:38 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=4859</guid>
		<description><![CDATA[I found myself in need of splitting an NSString into paragraphs. Or more precisely to analyze a string and find the NSRange for each such paragraph. At first I wrote a C-style function that looked for the &#8216;\n&#8217; in the NSString&#8217;s utf8String, but it turns out that this approach has problems with multi-character UTF8 sequences. For the longest time I shirked from using Blocks, which became part of iOS with iteration 4.0. But since this project will have a minimum deployment target of higher than this, I gained the ability to use a block-based enumeration function to achieve my goal with a record minimum of code. Label Buy an ad here Readability Serendipity helped me find that with this new substring enumeration function you can enumerate over a string&#8217;s substrings by words, lines, paragraphs or even sentences. And if you feel so inclined even reverse. Here&#8217;s my  code: - &#40;void&#41;buildParagraphRanges &#123; // get naked NSString NSString *string = &#91;self.attributedString string&#93;; &#160; // entire string NSRange range = NSMakeRange&#40;0, &#91;string length&#93;&#41;; &#160; NSMutableArray *tmpArray = &#91;NSMutableArray array&#93;; &#160; &#91;string enumerateSubstringsInRange:range options:NSStringEnumerationByParagraphs usingBlock:^&#40;NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop&#41; &#123; NSValue *value = &#91;NSValue valueWithRange:substringRange&#93;; &#91;tmpArray addObject:value&#93;; &#125; &#93;; &#160; self.paragraphRanges = tmpArray; &#125; As you can see there is an attributed string involved so at the very top I&#8217;ll have to get the plain NSString from this. In the middle I&#8217;ll do the enumeration and by converting the substringRange into an NSValue I can add it to an NSArray. This way I have the index location and length of each paragraph handy when I need it. We don&#8217;t know what goes on under the hood, but not having to do any kind of calculating to get the ranges can only be a good thing. Blocks work such that all local variables currently in scope when the method is called are still available inside the block. Additionally the parameters inside the ^() are also filled in for you to do with as you please. The block is sort of a function pointer on steroids. Since it is a parameter in this method you could even set up the block elsewhere and then just pass the block variable to it. But let&#8217;s not go overboard here. This is only the second time I get to use a method with a block and I&#8217;m lovin&#8217; it.]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/04/splitting-a-string-into-paragraphs-with-blocks/"></g:plusone></div><p>I found myself in need of splitting an NSString into paragraphs. Or more precisely to analyze a string and find the NSRange for each such paragraph. At first I wrote a C-style function that looked for the &#8216;\n&#8217; in the NSString&#8217;s utf8String, but it turns out that this approach has problems with multi-character UTF8 sequences.</p>
<p>For the longest time I shirked from using Blocks, which became part of iOS with iteration 4.0. But since this project will have a minimum deployment target of higher than this, I gained the ability to use a block-based enumeration function to achieve my goal with a record minimum of code.</p>
<p><span id="more-4859"></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>Serendipity helped me find that with this new substring enumeration function you can enumerate over a string&#8217;s substrings by words, lines, paragraphs or even sentences. And if you feel so inclined even reverse.</p>
<p>Here&#8217;s my  code:</p>

<div class="wp_codebox"><table><tr id="p4859176"><td class="code" id="p4859code176"><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>buildParagraphRanges
<span style="color: #002200;">&#123;</span>
    <span style="color: #11740a; font-style: italic;">// get naked 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><span style="color: #a61390;">string</span> <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self.attributedString <span style="color: #a61390;">string</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #11740a; font-style: italic;">// entire string</span>
    <span style="color: #a61390;">NSRange</span> range <span style="color: #002200;">=</span> NSMakeRange<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #002200;">&#91;</span><span style="color: #a61390;">string</span> length<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</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>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: #002200;">&#91;</span><span style="color: #a61390;">string</span> enumerateSubstringsInRange<span style="color: #002200;">:</span>range options<span style="color: #002200;">:</span>NSStringEnumerationByParagraphs usingBlock<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>substring, <span style="color: #a61390;">NSRange</span> substringRange, <span style="color: #a61390;">NSRange</span> enclosingRange, <span style="color: #a61390;">BOOL</span> <span style="color: #002200;">*</span>stop<span style="color: #002200;">&#41;</span>
     <span style="color: #002200;">&#123;</span>
         <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSValue_Class/"><span style="color: #400080;">NSValue</span></a> <span style="color: #002200;">*</span>value <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSValue_Class/"><span style="color: #400080;">NSValue</span></a> valueWithRange<span style="color: #002200;">:</span>substringRange<span style="color: #002200;">&#93;</span>;
         <span style="color: #002200;">&#91;</span>tmpArray addObject<span style="color: #002200;">:</span>value<span style="color: #002200;">&#93;</span>;
     <span style="color: #002200;">&#125;</span>
     <span style="color: #002200;">&#93;</span>;
&nbsp;
    self.paragraphRanges <span style="color: #002200;">=</span> tmpArray;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>As you can see there is an attributed string involved so at the very top I&#8217;ll have to get the plain NSString from this. In the middle I&#8217;ll do the enumeration and by converting the substringRange into an NSValue I can add it to an NSArray. This way I have the index location and length of each paragraph handy when I need it.</p>
<p>We don&#8217;t know what goes on under the hood, but not having to do any kind of calculating to get the ranges can only be a good thing.</p>
<p>Blocks work such that all local variables currently in scope when the method is called are still available inside the block. Additionally the parameters inside the ^() are also filled in for you to do with as you please. The block is sort of a function pointer on steroids. Since it is a parameter in this method you could even set up the block elsewhere and then just pass the block variable to it. </p>
<p>But let&#8217;s not go overboard here. This is only the second time I get to use a method with a block and I&#8217;m lovin&#8217; it. <img src='http://www.cocoanetics.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4859&amp;md5=7c40fc6994342271f46e1bbc749f50c1" 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/04/splitting-a-string-into-paragraphs-with-blocks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4859&amp;md5=7c40fc6994342271f46e1bbc749f50c1" type="text/html" />"
	</item>
		<item>
		<title>Cloning a Git Repo with Submodules</title>
		<link>http://www.cocoanetics.com/2011/03/cloning-a-git-repo-with-submodules/</link>
		<comments>http://www.cocoanetics.com/2011/03/cloning-a-git-repo-with-submodules/#comments</comments>
		<pubDate>Thu, 31 Mar 2011 10:23:55 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Recipes]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=4846</guid>
		<description><![CDATA[I was setting up a project with one submodule on my working iMac and was wondering how to do this most quickly. After tweeting the approach I had found, there where quickly some very smart people responding on how to do that better. I found this kind of crowd-sourced incremental improvement exhilarating, so I&#8217;m sharing it with you. Label Buy an ad here Readability Being a git beginner I started out with the slowest approach, one step after each other. git clone URL cd FOLDER git submodule init git submodule update This first clones the main project, then setup the submodule and then we have an update pull the submodule code. Simon Ljungberg was the first to point out that I could save one step by contracting both submodule commands like this. git clone URL cd FOLDER git submodule update --init The question did arise why the init would be necessary, but I found that if you don&#8217;t init the submodule then the update does not do anything and the submodule folder stays empty. We already thought to have found the shortest possible method, comes along Alex Blewitt and informs us that &#8211; provided you use git 1.6.5 or higher &#8211; the whole affair can also be shortend in a single line: git clone --recursive URL Of course we all use a git that is way newer than this minimum requirement, mine is 1.7.3.4 as of this writing. So let&#8217;s take notice of the elegance of the recursive option and use this from now on.]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/03/cloning-a-git-repo-with-submodules/"></g:plusone></div><p>I was setting up a project with one submodule on my working iMac and was wondering how to do this most quickly. After tweeting the approach I had found, there where quickly some very smart people responding on how to do that better. I found this kind of crowd-sourced incremental improvement exhilarating, so I&#8217;m sharing it with you.</p>
<p><span id="more-4846"></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">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>Being a git beginner I started out with the slowest approach, one step after each other.</p>

<div class="wp_codebox"><table><tr id="p4846180"><td class="code" id="p4846code180"><pre class="sh" style="font-family:monospace;">git clone URL
cd FOLDER
git submodule init
git submodule update</pre></td></tr></table></div>

<p>This first clones the main project, then setup the submodule and then we have an update pull the submodule code.</p>
<p><a href="https://twitter.com/styrisen">Simon Ljungberg</a> was the first to point out that I could save one step by contracting both submodule commands like this.</p>

<div class="wp_codebox"><table><tr id="p4846181"><td class="code" id="p4846code181"><pre class="sh" style="font-family:monospace;">git clone URL
cd FOLDER
git submodule update --init</pre></td></tr></table></div>

<p>The question did arise why the init would be necessary, but I found that if you don&#8217;t init the submodule then the update does not do anything and the submodule folder stays empty.</p>
<p>We already thought to have found the shortest possible method, comes along <a href="https://twitter.com/alblue">Alex Blewitt</a> and informs us that &#8211; provided you use git 1.6.5 or higher &#8211; the whole affair can also be shortend in a single line:</p>

<div class="wp_codebox"><table><tr id="p4846182"><td class="code" id="p4846code182"><pre class="sh" style="font-family:monospace;">git clone --recursive URL</pre></td></tr></table></div>

<p>Of course we all use a git that is way newer than this minimum requirement, mine is 1.7.3.4 as of this writing. So let&#8217;s take notice of the elegance of the <strong>recursive</strong> option and use this from now on.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4846&amp;md5=c5075908456f6f706cb340765fd37319" 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/03/cloning-a-git-repo-with-submodules/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4846&amp;md5=c5075908456f6f706cb340765fd37319" type="text/html" />"
	</item>
	</channel>
</rss>

