<?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>Jayway Team Blog &#187; objective-c</title>
	<atom:link href="http://blog.jayway.com/tag/objective-c/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 28 Jan 2012 15:53:55 +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>Invoke any Method on any Thread</title>
		<link>http://blog.jayway.com/2011/08/08/invoke-any-method-on-any-thread/</link>
		<comments>http://blog.jayway.com/2011/08/08/invoke-any-method-on-any-thread/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 08:03:16 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9143</guid>
		<description><![CDATA[I previously wrote a blog post titled Performing any Selector on the Main Thread detailing a convenience category on NSInvoication for easily creating invocation objects that could be invoked on any thread. This category has served me well, and even got traction in the iOS developer community, so I never bothered to stop and think [...]]]></description>
			<content:encoded><![CDATA[<p>I previously wrote a blog post titled <a href="http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/">Performing any Selector on the Main Thread</a> detailing a convenience category on <code>NSInvoication</code> for easily creating invocation objects that could be invoked on any thread.</p>
<p>This category has served me well, and even got traction in the <a href="http://iphonedevelopment.blogspot.com/2010/08/nsoperation-file-template-notes.html">iOS developer community</a>, so I never bothered to stop and think if there exist an even better solution.</p>
<p>Especially now that GDC exists, and doing an inline block to invoke on the main thread or a background queue is easier than ever before.</p>
<h3>Until Today</h3>
<p>Traveling home by bus as usual I got a flash of genius; <i>Why not use proxy objects?</i> Calling a method on the main thread should be no harder then this;</p>
<pre class="brush:objc">[[self.slider mainThreadProxy] setValue:0.5f animated:YES];</pre>
<p>The old <code>NSInvocation</code> solutions have a few drawbacks. First of all there is no code completion for the arguments, secondly there is not even basic type checking, and lastly the implementation is quite ABI specific.</p>
<p>The <code>NSObject</code> class already has support for method forwarding, and wrapping method calls up into <code>NSInvocation</code> instances. Why not use seriously battle proven code that Apple provides.</p>
<h3>The Skeleton</h3>
<p>The implementation for <code>-[NSObject mainThreadProxy]</code> will be childishly simple:</p>
<pre class="brush:objc">-(id)mainThreadProxy;
{
    // Return self directly if already on main thread.
    if ([NSThread isMainThread]) {
        return self;
    } else {
        return [CWMainProxy proxyWithTarget:self];
    }
}</pre>
<p>The <code>CWMainProxy</code> class is a simple private helper, that will perform all of the heavy lifting. The interface and life time code is very small:</p>
<pre class="brush:objc">@interface CWMainProxy : NSObject {
    id _target;
}
+(id)proxyWithTarget:(id)target;
@end

@implementation CWMainProxy

+(id)proxyWithTarget:(id)target;
{
    CWMainProxy* proxy = [[[self alloc] init] autorelease];
    proxy->_target = [target retain];
    return proxy;
}

-(void)dealloc;
{
    [_target release];
    [super dealloc];
}
@end
</pre>
<h3>The Meaty Parts</h3>
<p>Now comes the tricky parts; actually act like a proxy. The proxy is a simple <code>NSObject</code> subclass, first it needs to be able to fake to any caller that it can respond to everything that the proxies target responds to.</p>
<pre class="brush:objc">-(BOOL)respondsToSelector:(SEL)sel;
{
    return [super respondsToSelector:sel] ||
           [_target respondsToSelector:sel];
}</pre>
<p>Next up if the object claims it responds to a selector but do not have an actual implementation, then we must provide a <code>NSMethodSignature</code> so the run-time can create a proper <code>NSInvocation</code> for us.</p>
<pre class="brush:objc">-(NSMethodSignature*)methodSignatureForSelector:(SEL)sel;
{
    if ([_target respondsToSelector:self) {
        return [_target methodSignatureForSelector:sel];
    } else {
        return [super methodSignatureForSelector:sel];
    }
}</pre>
<p>And finally we need to actually forward the <code>NSInvocation</code> call to the main thread, as per the callers request:</p>
<pre class="brush:objc">-(void)forwardInvocation:(NSInvocation*)invocation;
{
    [invocation performSelectorOnMainThread:@selector(invokeWithTarget:)
                                 withObject:_target
                              waitUntilDone:YES];
}</pre>
<h3>Conclusions</h3>
<p>Given some thought I regard this solution to be much more elegant than my old solution. And it even yields less and more readable code than using GCD on iOS 4 and later:</p>
<pre class="brush:objc">[[self.slider mainThreadProxy] setValue:0.5f animated:YES];
    // vs
dispatch_async(dispatch_get_main_queue(),
               ^{
                   [self.slider setValue:0.5f animated:YES];
               });</pre>
<ul>
<li>The implementation is much smaller, and relies on the Foundation framework functionality, not my own Objective-C ABI hacks.</li>
<li>It is less code to write to use the functionality.</li>
<li>Xcode can do proper code completion and basic type checking.</li>
<li>It is compatible all the way back to iPhone OS 2, or Mac OS X 10.0, <a href="http://www.cocoanetics.com/2011/08/ios-versions-in-the-wild/">if you should care</a>.
 </ul>
<p>The <a href="https://github.com/Jayway/CWFoundation">CWFoundation project on Github</a> has a more complete implementation. With more support for optional blocking, delays, and more proxies not only for the main thread but also for background threads and operations queue.</p>
<p>You are seldom alone with great ideas, so a nod to <a href="http://twitter.com/#!/nevyn">Joachim Bengtsson</a> who has written about an <a href="http://overooped.com/post/913725384/nsinvocation">invocation grabber</a> before.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/08/08/invoke-any-method-on-any-thread/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Auto-incrementing Build Numbers in Xcode</title>
		<link>http://blog.jayway.com/2011/05/31/auto-incrementing-build-numbers-in-xcode/</link>
		<comments>http://blog.jayway.com/2011/05/31/auto-incrementing-build-numbers-in-xcode/#comments</comments>
		<pubDate>Tue, 31 May 2011 13:20:53 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8586</guid>
		<description><![CDATA[Users and testers will find bugs you are sure you have already fixed. Sometimes they use the wrong version, sometimes your fix is not as good as you thought. Either way a tiny unique version number visible in the app can save you hours of work. Incrementing the version number of your project for every [...]]]></description>
			<content:encoded><![CDATA[<p>Users and testers will find bugs you are sure you have already fixed. Sometimes they use the wrong version, sometimes your fix is not as good as you thought. Either way a tiny unique version number visible in the app can save you hours of work.</p>
<p>Incrementing the version number of your project for every small update is often not feasible, if it involves manual labor it just does not get done. Would it not be nice if Xcode just autoincremented a build number for you every time you build? </p>
<h3> This can be done</h3>
<p>There are dozens of solution to the problem available by Google. Unfortunately most do not work in both Xcode 3.2 and Xcode 4, and many more require a lot of hacking, even running external Perl or Python scripts. Using avgtool seems to be a major overkill for most use-cases. There must be an easier way, and there is.</p>
<p>What we want to do is to have the build number available in our Info.plist file, so that it can be read and displayed at run-time. And we also want Xcode to automatically increment this number for every build.</p>
<p>Add a key named <code>CWBuildNumber</code> to your Info.plist file, and set it to a sane start value, maybe "0". You can load it at run-time with a short statement like:</p>
<pre class="brush:objc">NSString* buildNumber = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CWBuildNumber"];</pre>
<p>Both Xcode 3.2 and Xcode 4 allows to add a <em>Run Script</em> phase to any target. Unfortunately Xcode 3.2 and 4 run these scripts with different paths. <code>PROJECT_DIR</code> environment variable to the rescue! Secondly we want to rewrite the target's source Info.plist file, not the file bundled with the application, so make sure to order the script phase before the <em>Copy Resources</em> phase. Then just add this tiny script phase to your target build:</p>
<pre class="brush:shell">buildNumber=$(/usr/libexec/PlistBuddy -c "Print CWBuildNumber" ${PROJECT_DIR}/MyApp-Info.plist)
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CWBuildNumber $buildNumber" ${PROJECT_DIR}/MyApp-Info.plist </pre>
<h3>Conclusions</h3>
<p>Happy developers, and happy tester. Maybe even happy users, if you choose to show the full version number including build number in the final product.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/05/31/auto-incrementing-build-numbers-in-xcode/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>The state of iOS Open Source &#8211; and what to do about it!</title>
		<link>http://blog.jayway.com/2011/05/16/the-state-of-ios-open-source-and-what-to-do-about-it/</link>
		<comments>http://blog.jayway.com/2011/05/16/the-state-of-ios-open-source-and-what-to-do-about-it/#comments</comments>
		<pubDate>Mon, 16 May 2011 14:43:28 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8432</guid>
		<description><![CDATA[There is a vibrant community of open source projects for iOS. You need a calendar UI components or a JSON parser? No problem, the projects are out there. Most code out there is of very high quality. Unfortunately the distribution of the code is generally very crude, barely half a step away from sharing code [...]]]></description>
			<content:encoded><![CDATA[<p>There is a vibrant community of <a href="https://github.com/search?q=iphone">open source projects for iOS</a>. You need a calendar UI components or a JSON parser? No problem, the projects are out there. Most code out there is of very high quality. Unfortunately the distribution of the code is generally very crude, barely half a step away from sharing code on disks or uploading a ZIP-archive to a BBS.</p>
<h3>The Current State of Affairs</h3>
<p>Most Open Source projects for iOS are distributed as a source code repository with an <a href="http://developer.apple.com/library/ios/featuredarticles/XcodeConcepts/Concept-Projects.html">Xcode projec</a>t. But here the good news stop for most projects. The Xcode project usually only has one <a href="http://developer.apple.com/library/ios/featuredarticles/XcodeConcepts/Concept-Targets.html">target</a>, a sample project, mixing the reusable code in the same bucket as the sample/incubator code around it.</p>
<p>The usage instructions suggest you drag and drop a directory, or even worse a collection of files, into your own project. This is a very primitive solution, passable in the '80s when all we had was disks and BBS:es, not good enough today. All history and connection back to the source is lost, any value added by source control systems is lost the second you decide to use an open source component this way. Any bug-fix or improvement you make will require a manual merge back to the original project. You also loose all tracking information the moment you copy a file, what version of project X did you use, some special branch?</p>
<h3>This Need To Change</h3>
<p>This affair also highly discourages re-use. Almost every open source project out there that involves network connectivity also uses <a href="http://developer.apple.com/library/ios/samplecode/Reachability/">Apple's Reachability example</a> code as a base for determining network status. Apple's code is not complete for all use-cases, and not free of bugs, so almost every project has a more or less modified variant of the same code causing compiler errors. Ensuring that using several open source project in one application is bound to end up with conflicts. Leaving it up to you to determine which projects version of Reachability that is the master version, often you end up writing a third version of Reachability for your project. And none of these changes and improvements will ever end up in a re-usable way for the iOS community as a whole.</p>
<p>This is not an impossible problem to solve, in the Java world there is for example <a href="http://maven.apache.org/">Maven</a> that solves this very well. Maven is a huge tool, and re-inventing that wheel for iOS would be a mammoth task. Fortunately that is not needed; Xcode already has the basics that we need in order to create iOS projects that are highly extendable and re-usable.</p>
<h3>There is a Solution Today</h3>
<p>One Xcode project can have one or more targets, usually the target is your application, sometimes you have one target for iPhone and a separate target for iPad. Targets are not limited to applications, you can also have a Unit-test targets, and more importantly static library targets.</p>
<p>A static library target yield a static library that can be linked into any other target, so be applications or other static libraries. A static library is a cruder version of a Framework, like UIKit and Core Data that Apple provide us. Crude as they are, it is still good enough to use for sharing re-usable Open Source project components.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/sub-projects.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/sub-projects.png" alt="" title="Xcode sub projects" width="299" height="303" align="right" /></a>A Xcode project has the notion of sub-projects. A Xcode sub-project is a reference to another Xcode project. You can set the sub-project's Targets as direct dependencies for your targets, and instruct the sub-projects products to be linked with your products. In essence say "Use what that other Xcode project creates to build my project".</p>
<p>The idea of Xcode's sub-projects has a logical one-on-one mapping to sub-modules in Git. Meaning that exposing re-usable iOS Open Source projects as static libraries on for example github is as easy as can be.</p>
<h3>Eating Your Own Dogfood</h3>
<p>This is actually what I have done for years, ever since I released HessianKit in 2008. Most of the code you write will be re-usable for the next project, having an easy way group your re-usable components into a growing library will save you a lot of work.</p>
<p>Firstly I never have to start with a blank canvas for any project. But more importantly, when working on many applications, any bug fixes and improvements I make to my shared components immediately trickles out to all other projects as well. If I add animated insert of cells in my column table view for project <em>A</em>, then all other projects is only one git pull away from benefiting from this new feature as well.</p>
<p>Jayway have since a few weeks begun the process of publishing our re-usable components for iOS. So far this has resulted in three projects on github:</p>
<ul>
<li><a href="https://github.com/jayway/CWFoundation">CWFoundation</a> - a collection of new classes and categories to add functionality that is commonly missing from Foundation framework.</li>
<li><a href="https://github.com/jayway/CWUIKit">CWUIKit</a> - a collection of classes and categories that do the same for UIKit. CWUIKit requires CWFoundation.</li>
<li><a href="https://github.com/jayway/CWCoreData">CWCoreData</a> - A collection of categories for Core Data that makes using Core Data in a multithreaded application a breeze.</li>
</ul>
<p>These are living projects and will be updated with new functionally over time, and large enough to warrant a blog-post for each on their own. There are also a few <i>Componentized</i> forks of popular iOS open source projects at <a href="https://github.com/jayway">Jayway's github page</a>. </p>
<h3>Tutorial for Using a Sub-Project from a Sub-Module</h3>
<p>Working with an environment like this have many benefits, but also requires some knowledge of both Xcode and git. There are a few gotchas to be aware of, limitation of Xcode and the linker, best explained with a short tuturial.</p>
<p>CWUIKit has additions to UIAlertView that allows an alert to be created directly from a <code>NSError</code> instance, just like AppKit do on Mac OS X. Lets walk through how to create a new project that uses this functionality from CWUIKit to display the error message from a faulty URL request.</p>
<blockquote><p>This tutorial is for Xcode 3.2, but works with minor modifications for Xcode 4. Changes for Xcode 4 are written in block quotes like this.</p></blockquote>
<h4>1. Create new "Window-based Application" from Xcode.</h4>
<p>   I chose a Window-based app because it contains the least amount of template code, and fits the purpose of an example well.</p>
<h4>2. Initialize the project directory as a git repo.</h4>
<pre class="brush:shell">git init</pre>
<p>We need to initialize the project directory as a proper git-repo in order to use git's sub-modules.</p>
<blockquote><p>Skip this step if project is created with git-repo in Xcode 4.</p></blockquote>
<h4>3. Add sub-module</h4>
<pre class="brush:shell">git submodule add git@github.com:jayway/CWUIKit.git Components/CWUIKit</pre>
<p>This will create a sub directory named <em>Components</em>, this is where I by convention put all my sub-modules/sub-projects, it is not a hard requirement.</p>
<h4>4. Update and initialize all submodules</h4>
<pre class="brush:shell">git submodule update --init --recursive</pre>
<p>A git-submodule is by default not initialized, this is to avoid downloading large amount of data for a sub-modules you do not need, such as a test project. This is why we must update and initialize the sub-projects to realize them when starting a new repo or cloning an old one.</p>
<h4>5. Add sub-project</h4>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/target-membership.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/target-membership.png" alt="" title="Target Membership" width="265" height="163" align="right" /></a><br />
Locate <em>CWUIKit.xcodeproj</em> and drag and drop into your project.<br />
Highlight the <em>CWUIKit.xcodeproj</em> item and ensure the <em>"Target Membership"</em> column, that has a bullet as symbol, is checked for the libCWUIKit.a product. This is the static library to link against.<br />
  Also add the CWUIKit target as a direct dependency to your applications target so that CWUIKit is automatically build before building your application.</p>
<blockquote><p>It is not required to setup target membership in Xcode 4, only set Target as Target Dependency in Build Phases tab, and add the Product to be linked in the same tab.</p></blockquote>
<h4>6. Recursive Sub-Projects</h4>
<p>Static libraries are by their nature linked into your binary, this means that if <em>static lib A</em> and <em>static lib B</em> both define the same <em>global symbol C</em> you will get a duplicate symbol <em>‘C’</em> error when linking you app.<br />
CWUIKit uses functionality from CWFoundation, but because of this limitation of the linker it can not explicitly add this functionality to itself. Doing so would make it impossible to use CWUIKit side-by-side with other projects that also uses CWFoundation, such as CWCoreData.<br />
The work around is that any project that includes CWUIKit must also include CWFoundation. So repeat step 5 with the <em>CWFoundation.xcodeproj</em> from <em><Your Appl Directory>/Components/CWUIKit/Components/CWFoundation</em>.</p>
<blockquote><p>Xcode 4 has full knowledge of recursive sub-projects, so this step can be skipped. Only add CWFoundation sub-projects product to be linked.</p></blockquote>
<h4>7. Add QuartzCore and OpenGLES frameworks to your target.</h4>
<p>Static libraries can not enforce linking of frameworks on it’s own, so building the app in it’s current state would result in missing symbols errors.<br />
Using CWUIKit requires the app to be linked against QuartzCore and OpenGLES frameworks for CoreAnimation and OpenGL additions.</p>
<h4>8. Setup header search paths.</h4>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/header-search.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/header-search.png" alt="" title="Header Search Path" width="304" height="91" align="right" /></a>Unfortunately sub-projects headers are not automatically added to the search path of your projects. So you must add <em>"Components/**"</em> as a header search path for your project.</p>
<blockquote><p>Xcode 4 considers header search baths to be an advanced setting, to change the build settings display for Basic to All if you can not find it.</p></blockquote>
<h4>9. Setup linker flags</h4>
<p>Add "-all_load" to other linker flags.<br />
The GCC and LLVM linker also has a limitation/bug for static libraries that will strip out any methods for categories on a class that is not defined in the static library. For example any method extending <code>UIAlertView</code> in libCWUIKit.a will be stripped out by this bug.</p>
<h4>10. Add <code>#import "CWUIKit.h"</code> to you application delegate. And add this small code to the <code>application:didFinishLaunchingWithOptions:</code> method</h4>
<pre class="brush:objc">NSError* error = nil;
[NSData dataWithContentsOfFile:@"wrong path!"
                       options:nil
                         error:&error];
[[UIAlertView alertViewWithError:error] show];</pre>
<h4>11. There is no step 11.</h4>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/error-alert.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/error-alert.png" alt="" title="UIAlertView with NSError additions" width="198" height="372" align="right" /></a><br />
But there is a screenshot of the running app.</p>
<h3>Conclusions</h3>
<p>This method of using Xcode sub-projects and git sub-modules for managing shared components works very well, and scales to be even better the more sub-projects and developers you have. The greatest benefit is without any doubt that bug-fixes and new features by default always trickles back to their source and become re-usable for all.</p>
<p>All the downsides are in the limitations of static libraries themselves, and can unfortunately not be overcome unless Apple introduces proper support for third party frameworks in iOS SDK. The two major gotchas are missing symbols caused by missing frameworks required by dependencies, and duplicate symbols caused by implicit inclusion of dependencies from dependencies. I have found that the best solution is to always have a README with your project where you explicitly name each Framework and Component that is required.</p>
<p>Using Xcode sub-project to manage your builds solves the problem of dependency resolution without the need to write a new system, works on the developer's desktop as well as on a build server. Using git sub-modules to manage your dependencies solves the problem of including all recursive dependencies as well as versioning. Any sub-module can by locked at a particular stable version by commit or tag as required, with full history. But best of all; you as a developer is free to just code away knowing that you can later commit and push your changes back, independently of how or where the code originates.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/05/16/the-state-of-ios-open-source-and-what-to-do-about-it/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Sync-Async Pair Pattern &#8211; Easy concurrency on iOS</title>
		<link>http://blog.jayway.com/2011/04/28/sync-asyn-pair-pattern-easy-concurrency-on-ios/</link>
		<comments>http://blog.jayway.com/2011/04/28/sync-asyn-pair-pattern-easy-concurrency-on-ios/#comments</comments>
		<pubDate>Thu, 28 Apr 2011 09:10:19 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8208</guid>
		<description><![CDATA[Apple provides many tools for implementing concurrency in your application. NSOperationQueue, GCD, or simply using performSelectorInBackground:withObject: that is available on each and every object, are just some examples. The tools are there, yet implementing good concurrency is hard. The solution I have found is not yet another tool, or framework, but a simple pattern. I [...]]]></description>
			<content:encoded><![CDATA[<p>Apple provides many tools for implementing concurrency in your application. <code>NSOperationQueue</code>, GCD, or simply using <code>performSelectorInBackground:withObject:</code> that is available on each and every object, are just some examples. The tools are there, yet implementing good concurrency is hard.</p>
<p>The solution I have found is not yet another tool, or framework, but a simple pattern. I have not found an existing name for the pattern so I call it Sync-Async Pair. The idea is to hide the complexity of asynchronous calls and call-back behind a facade, and have a straightforward synchronous implementation. An implementation that is easy to write, test and extend.</p>
<h3>Sync-Async Pair Pattern</h3>
<p>As the name suggests the pattern consist of a method pair, one is synchronous, and the other is asynchronous. The asynchronous method is backed by the synchronous implementation, and is only responsible for erecting a simplified facade in front of the sometimes complex concurrent implementation. </p>
<p>The first priority is to expose a clean API, the second priority is an implementation that is simple, testable and maintainable. Turns out that beginning with a clean API design (how to use the code), steers you towards a clean implementation (how to write the code). Most developers do the mistake to first write the code, and then struggle to try to use their own code.</p>
<p>Sync-Asyn Pair begins by defining a public API that then steers towards a clean implementation. Let's assume we are implementing some kind of a book reader. We need two model objects; <code>CWBook</code> and <code>CWChapter</code>. Both books and chapters are fetched from the network, so we need concurrency in order to not block the UI thread.</p>
<p>For this example let's focus only on fetching the chapters associated with a book. All other operations would be implemented in a similar fashion. First we need a public API, two methods for the sync-async pair on <code>CWBook</code>, and a delegate protocol.</p>
<pre class="brush:objc">@protocol CWBookFetchChaptersDelegate &lt;NSObject&gt;
-(void)bookDidFetchChapters:(CWBook*)book;
-(void)book:(CWBook*)book failedFetchChaptersWithError:(NSError*)error;
@end
// ...
-(BOOL)fetchChaptersWithError:(NSError**)error;
-(void)fetchChaptersWithAsyncDelegate:(id&lt;CWBookFetchChaptersDelegate&gt;)delegate;
</pre>
<p>The synchronous method <code>fetchChaptersWithError:</code> is very straightforward to implement.</p>
<pre class="brush:objc">-(BOOL)fetchChaptersWithError:(NSError**)error;
{
    NSURL* url = [self URLForFetchingChapters];
    NSData* data = [NSData dataWithContentsOfURL:url
                                         options:0
                                           error:error];
    if (data) {
        return [self parseChaptersFromData:data
                                     error:error];
    }
    return NO;
}</pre>
<p>How to construct the <code>NSURL</code>, or possibly <code>NSURLRequest</code> is not important. Nor is it important how you actually parse the resulting data sent from the server, that is totally left to our problem domain. Just make it synchronous and super easy to write automatic unit checks for!</p>
<h3>Adding Concurrency</h3>
<p>Now to the hard part, that is actually quite manageable; adding the concurrency. For this example I will use <code>performSelectorInBackground:withObject:</code>. Your specific implementation might need <code>NSOperationQueue</code>, or GCD if you have special needs such as queues or cancelable operations. The idea will remain the same.</p>
<p>The most basic, and common, implementation for the public async method simply fires off the concurrent operation:</p>
<pre class="brush:objc">-(void)fetchChaptersWithAsyncDelegate:(id&lt;CWBookFetchChaptersDelegate&gt;)delegate;
{
    [self performSelectorInBackground:@selector(fetchChaptersWithDelegate:)
                           withObject:delegate];
}</pre>
<p>In most cases all it does is request a private method to be performed on a background thread at some point in time. This is also the perfect place to abort operations early, for example a no-op if a request such as fetching a thumbnail is already in progress.</p>
<p>The private method previously launched is where most of the work is done. This is where a <code>NSAutoreleasePool</code> is setup, the synchronous method is called, and the delegate is properly called on the proper thread. The basic implementation for fetching books would be:</p>
<pre class="brush:objc">-(void)fetchChaptersWithDelegate:(id&lt;CWBookFetchChaptersDelegate&gt;)delegate;
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    NSError* error = nil;
    BOOL success = [self fetchChaptersWithError:&error];
    if (success) {
        [[NSInvocation invocationWithTarget:delegate
                                   selector:@selector(bookDidFetchChapters:)
                            retainArguments:YES, self] invokeOnMainThreadWaitUntilDone:NO];
    } else {
        [[NSInvocation invocationWithTarget:delegate
                                   selector:@selector(book:failedFetchChaptersWithError:)
                            retainArguments:YES, self, error] invokeOnMainThreadWaitUntilDone:NO];
    }
    [pool release];
}</pre>
<p>For this example I am using my <code>NSInvocation</code> additions to perform the delegate callbacks to the main thread, but it could just as easily been done using GCD. The additions are described in detail and available for download in <a href="http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/">this blog post</a>, or from in the <a href="https://github.com/jayway/CWFoundation">CWFoundation repo on github</a>.</p>
<p>As you can see the boiler plate code for managing concurrency is actually very minimal, much less than 10 statements in total. The boilerplate code is almost reduced to only calling other methods, leaving very very few opportunities for bugs to sneak in.</p>
<h3>Core Data in the Mix</h3>
<p>The Sync-Async Pair pattern also lend itself beautifully for writing multi-threaded Core Data. The hassle of juggling <code>NSManagedObjectID</code> and <code>NSManagedObject</code> instances from different contexts can be completely left up to the private implementation that calls the synchronous method.</p>
<p>The private method responsible for calling the synchronous method and handling callbacks could be implemented as such:</p>
<pre class="brush:objc">-(void)notifyDelegate:(id)delegate ofSuccess:(BOOL)success withError:(NSError*)error;
{
    self = [[NSManagedObjectContext threadLocalContext] objectWithID:[self objectID]];
    if (success) {
        [delegate bookDidFetchChapters:self];
    } else {
        [delegate book:self failedFetchChaptersWithError:error];
    }
}

-(void)fetchChaptersWithDelegate:(id&lt;CWBookFetchChaptersDelegate&gt;)delegate;
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    self = [[NSManagedObjectContext threadLocalContext] objectWithID:[self objectID]];
    NSError* error = nil;
    BOOL success = [self fetchChaptersWithError:&error];
    [[NSInvocation invocationWithTarget:self
                               selector:@selector(notifyDelegate:ofSuccess:withError:)
                        retainArguments:YES, delegate, success, error] invokeOnMainThreadWaitUntilDone:NO];
    [pool release];
}</pre>
<p>Not much extra code, and the ugliness of handling Core Data's managed contexts is neatly hidden for clients at a single point in the code, that is much easier to test, debug, and maintain than most conventional Core Data code.</p>
<h3>Conclusions</h3>
<p>The simple Sync-Async Pair pattern makes it easy to write robust concurrent code. It is even a pattern that by design yields an elegant public API. It is also very easy to test, extend and even change the internal implementation completely without affecting any clients.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/04/28/sync-asyn-pair-pattern-easy-concurrency-on-ios/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Exceptions and Errors on iOS</title>
		<link>http://blog.jayway.com/2010/10/13/exceptions-and-errors-on-ios/</link>
		<comments>http://blog.jayway.com/2010/10/13/exceptions-and-errors-on-ios/#comments</comments>
		<pubDate>Wed, 13 Oct 2010 12:03:16 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6430</guid>
		<description><![CDATA[Cocoa, and by inheritance Cocoa Touch on iOS makes a clear distinction between what is an exception, and what is an error in your application. This should be obvious since NSException and NSError both inherit from the NSObject root class with no relations at all. Programmer vs. User Exceptions are intended for signaling programming errors [...]]]></description>
			<content:encoded><![CDATA[<p>Cocoa, and by inheritance Cocoa Touch on iOS makes a clear distinction between what is an exception, and what is an error in your application. This should be obvious since <code>NSException</code> and <code>NSError</code> both inherit from the <code>NSObject</code> root class with no relations at all.</p>
<h3>Programmer vs. User</h3>
<p>Exceptions are intended for signaling programming errors and fatal errors that the application can never recover from. One such error is index out of bounds when accessing an array. There is little reason to catch any exception; if you for example could not calculate a legal array index the first time around your app is in an illegal state. Exceptions are for your own use as a developer, to catch all programming errors in testing before shipping to the end user. Only secondary to inform the user of fatal errors when possible.</p>
<p>Errors are intended for signaling user errors, and conditions that can not be predicted until the end user runs your application. One such error is network timeout. There are many reasons to catch these errors; e.g. the user could be asked to check the network connectivity, and try again. Errors should always be handled, and be properly presented to the user. A user is much more forgiving if your application fails with a clear reason, than if it simply crashes or refuses to work.</p>
<h3>Signal and Handle Exceptions</h3>
<p>Exceptions are thown in Objective-C, just as in most other programming languages. You can construct your <code>NSException</code> object manually, and throw it using the <code>@throw</code> compiler directive if you like. But the preferred way is to use the <code>NSException</code> convenience class methods.</p>
<pre class="brush: objc">[NSException raise:NSInvalidArgumentException
            format:@"Foo must not be nil"];
</pre>
<p>Here we see the first divergence from how for example Java and C# handles exceptions. In Objective-C different exceptions are not normally signaled by different subclasses, but instead the exception is given a name, in the form of a constant string. Exceptions are however handled quite traditionally.</p>
<pre class="brush: objc">@try {
    // Normal code flow, with potential exceptions
}
@catch (NSException* e) {
    // Handle exception or re-throw
}
@finally {
    // Mandatory cleanup
}</pre>
<h3>Signal and Handle Errors</h3>
<p>Errors do not use any special feature of the Objective-C run-time or programming language. Errors are instead treated as normal method arguments.</p>
<p>For synchronous tasks the error is returned as the last out argument of the method. A typical synchronous method signature with error handling looks like this:</p>
<pre class="brush: objc">- (id)initWithContentsOfURL:(NSURL *)url
                      error:(NSError **)outError</pre>
<p>The client of such a task can always pass <code>NULL</code> to explicitly ignore the details of the error, the method must therefor also signal the error by the return value. This is typically done by returning <code>nil</code>, or <code>NO</code> if no other return value should exist. Ignoring the error is never recommended.</p>
<p>For asynchronous tasks the error is returned as the last argument of a delegate method. A typical asynchronous method signature with error handling looks like this:</p>
<pre class="brush: objc">- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error</pre>
<p>The client of such a task can never opt out of receiving the error. It is still never recommended to ignore the error.</p>
<p>The information in an <code>NSError</code> is always localized and phrased in end-user friendly words. This is something you can trust of errors from system frameworks, and a hard requirement on you when you create your own errors. Therefor handling the error is never a burden, in the simplest case you can simply display the localized error message to the end user and call it a day.</p>
<pre class="brush: objc">- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
	[[[[UIAlertView alloc] initWithTitle:[error localizedDescription]
                                 message:[error localizedFailureReason]
                                delegate:nil
                       cancelButtonTitle:NSLocalizedString(@"OK", nil)
                       otherButtonTitles:nil] autorelease] show];
}</pre>
<h3>There is more to <code>NSError</code></h3>
<p>Cocoa and Cocoa Touch have much in common. Classes not brought straight over from Mac OS X to iOS often have a sibling anyway. One such class is <code>NSAlert</code> from Mac OS X and it's sibling <code>UIAlertView</code> on iOS. They serve the same purpose of displaying an alert message to the end user, optionally with a few choices in the form of buttons.</p>
<p>One convenience method for handling errors on Mac OS X is <code>-[NSAlert alertWithError:]</code>, it did not survive the transformation to <code>UIAlertView</code> on iOS. It is a pity, since it is a convenient way to quickly setup an alert with all the localized and human readable information. Basically turning the example code for handling an asynchronous error above from five lines of code, into a single line of code.</p>
<p>But that is not all. <code>NSAlert</code> and <code>NSError</code> on Mac OS X also have standardize facilities for handling recovery options. For example adding a <em>"Retry"</em> button to the alert, and calling the correct methods in response to this user selection.</p>
<p>On iOS <code>NSError</code> still have all the facilities to handle error recoveries, it is only <code>UIAlertView</code> that is lacking the final user facing bits. Fortunately this is easy to add. <code>NSError</code> manages error recovery with information held in it's userInfo dictionary. The following keys are used:
<ul>
<li><code>NSLocalizedRecoverySuggestionErrorKey</code> - A localized text with a general suggestion for how to recover from the error, for example <em>"Check the network connection"</em>.</li>
<li><code>NSLocalizedRecoveryOptionsErrorKey</code> - An array of localized button titles such as <em>"Retry"</em>.</li>
<li><code>NSRecoveryAttempterErrorKey</code> - An object conforming to the informal protocol <code>NSErrorRecoveryAttempting</code>.</li>
</ul>
<p>The informal protocol <code>NSErrorRecoveryAttempting</code> declares one method that is significant for iOS:</p>
<pre class="brush: objc">- (BOOL)attemptRecoveryFromError:(NSError *)error
                     optionIndex:(NSUInteger)recoveryOptionIndex</pre>
<p>The <code>recoveryOptionIndex</code> is the index into the array of button titles, and is the actual choice the user made for recovering from the error.</p>
<p>Adding a <code>-[UIAlertView alertWithError:]</code> convenience method to UIAlertView is made really easy since Objective-C has categories, and classes themselves are object instances so we can use the <code>UIAlertView</code> class as alert delegate for error recovery alerts.</p>
<pre class="brush: objc">@implementation UIAlertView (CWErrorHandler)

static NSMutableDictionary* cw_recoveryErrors = nil;

+(void)alertViewCancel:(UIAlertView *)alertView;
{
    NSValue* key = [NSValue valueWithPointer:(const void *)alertView];
    [cw_recoveryErrors removeObjectForKey:key];
}

+ (void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex;
{
    NSValue* key = [NSValue valueWithPointer:(const void *)alertView];
    NSError* error = [cw_recoveryErrors objectForKey:key];
	NSString* buttonTitle = [alertView buttonTitleAtIndex:buttonIndex];
    NSInteger recoveryIndex = [[error localizedRecoveryOptions]
                                   indexOfObject:buttonTitle];
    if (recoveryIndex != NSNotFound) {
	    [[error recoveryAttempter]
             attemptRecoveryFromError:error
                          optionIndex:recoveryIndex];
    }
    [cw_recoveryErrors removeObjectForKey:key];
}

+(UIAlertView*)alertViewWithError:(NSError*)error;
{
    UIAlertView* alert = [UIAlertView alloc];
    [[alert initWithTitle:[error localizedDescription]
                  message:[error localizedFailureReason]
                 delegate:nil
        cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
        otherButtonTitles:nil] autorelease];
    if ([error recoveryAttempter]) {
    	if (cw_recoveryErrors == nil) {
			cw_recoveryErrors = [[NSMutableDictionary alloc]
                                     initWithCapacity:4];
        }
        NSValue* key = [NSValue valueWithPointer:(const void *)alertView];

        [cw_recoveryErrors setObject:error
                              forKey:key];
        for (id recoveryOption in [error localizedRecoveryOptions]) {
        	[alert addButtonWithTitle:recoveryOption];
        }
        alert.delegate = (id)self;
    }
    return alert;
}

@end</pre>
<h3>Conclusion</h3>
<p>The clean separation of exceptions and errors help you as a developer to catch programming errors during development and with unit tests, and also handle errors of interest to the end users in a standardized and uniform way. The very nature of <code>NSError</code> encourages developers to write descriptive error messages that end users can understand and make informed discussions about. Errors are unavoidable in any application of non-neglectable complexity, gracefully handling these errors gives an aura of quality and ensures happy users. Happy users means better sales.</p>
<p>Full source code to the examples in this post, including some more convenience methods can be <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/10/UIAlertView+CWErrorHandler1.zip'>downloaded here</a>, and are released under the Apache 2 open source license. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/10/13/exceptions-and-errors-on-ios/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Future Cocoa Operation</title>
		<link>http://blog.jayway.com/2010/08/19/future-cocoa-operation/</link>
		<comments>http://blog.jayway.com/2010/08/19/future-cocoa-operation/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 17:51:30 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6051</guid>
		<description><![CDATA[In Java you have for quite some time had the Future interface for encapsulating an asynchronous calculation. Cocoa has had the abstract NSOperation class to encapsulate asynchronous operations. NSOperation do not have any facilities for returning a result when done as the Future do, you are left to implement this on your own. Which I [...]]]></description>
			<content:encoded><![CDATA[<p>In Java you have for quite some time had the <code><a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Future.html">Future</a></code> interface for encapsulating an asynchronous calculation. Cocoa has had the abstract <code><a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html">NSOperation</a></code> class to encapsulate asynchronous operations.</p>
<p><code>NSOperation</code> do not have any facilities for returning a result when done as the <code>Future</code> do, you are left to implement this on your own. Which I have done a few times, and as a rule of thumb, make the solution generic when needed for the third time.</p>
<p>Operations works perfectly for background network activities. One common network activity is search-as-you-type, in this case you need to also cancel the previous operation if it has not yet been completed, so lets built this behavior into the generic solution as well.</p>
<h3>API Design</h3>
<p>What we want is an subclass of <code>NSOperation</code> that provides a future result, lets call this class <code>CWFutureOperation</code>. It is abstract, so users are supposed to subclass and implement <code>main</code> method just as for <code>NSOperation</code>, only difference is that the main method implementation must call <code>setResult:</code> before exiting.</p>
<p>The result that is set in the main method implementation can then be fetched using the blocking method <code>result</code>, equivalent to <code>get()</code> from the Java <code>Future</code>. As an alternative we would also like to be handed the method upon completion via a target-action pair. If the target-action pair is only called for finished operations that are not cancelled, then we get the search-as-you-type behavior for free.</p>
<p>It is also nice to be able to wrap up any method returning an object in a future operation as a convenience, so lets add that as well to our class interface:</p>
<pre class="brush:objc">@interface CWFutureOperation : NSOperation {
@private
    id _result;
    BOOL _isResultSet;
    id _completionTarget;
    SEL _completionSelector;
}

-(id)result;
-(void)setCompletionTarget:(id)target selector:(SEL)selector;
-(void)setResult:(id)result;

+(CWFutureOperation*)operationWithTarget:(id)target
                                selector:(SEL)selector
                                  object:(id)object;

+(CWFutureOperation*)operationWithInvocation:(NSInvocation*)invocation;

@end</pre>
<h3>Implementation</h3>
<p>The client of the code must be able to fetch the result and the <code>CWFutureOperation</code> subclass must be able to set the result. The <code>result</code> method should block until the operation is finished if needed, and must properly return a result that can survive the operation that might be in a release pool. The implementation for this is straight forward, only minor complexity added in order to allow the result to be set multiple times:</p>
<pre class="brush:objc">-(id)result;
{
    if (![self isFinished]) {
        [self waitUntilFinished];
    }
    if ([self isCancelled]) {
        return nil;
    }
    return [[_result retain] autorelease];
}

-(void)setResult:(id)result;
{
    _isResultSet = YES;
    if (_result != result) {
        [_result autorelease];
        _result = [result retain];
    }
}</pre>
<p>The reason that we flag if the result has been set is because we want to throw an exception if the subclass implementation of the main method failes to set the result before exiting, we add this behavior by overriding the start method in <code>CWFutureOperation</code>.</p>
<p>The <code>start</code> method will also call the target-action pair upon completion if the operation has not been cancelled. The target selector is always called on the main thread, this is so that we safely can update any UI using the calculated result without adding even more threading code.</p>
<pre class="brush:objc">-(void)start;
{
    [super start];
    if (![self isCancelled]) {
        if (!_isResultSet) {
            [NSException raise:NSInternalInconsistencyException
                        format:@"%@ did not set result.", self];
        }
        [_completionTarget performSelectorOnMainThread:_completionSelector
                                            withObject:self
                                         waitUntilDone:NO];
    }
}</pre>
<h3>Conclusion</h3>
<p>The total amount of code is not mu<a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/08/Futures.zip'>Futures</a>ch, but this generic class adds a pattern to follow making design decisions for new application easy and consistent.</p>
<p>Solving the age old search-as-you-type problem can be as simple as this (Many assumptions, but you get the idea):</p>
<pre class="brush:objc">-(NSArray*)performSearchWithString:(NSString*)str;
{
    NSMutableArray* searchResults = nil;
    // Do actual search over the interwebz.
    return searchResults;
}

-(void)searchOperationDidComplete:(CWFutureOperation*)op;
{
    self.currentSearchOperation = nil;
    self.currentSearchResult = [op result];
    [self.searchDisplayController.searchResultsTableView reloadData];
}

-(BOOL)searchDisplayController:(UISearchDisplayController*)controller
  shouldReloadTableForSearchString:(NSString*)searchString;
{
	CWFutureOperation* op = [CWFutureOperation operationWithTarget:self
                                                          selector:@selector(performSearchWithString:) object:searchString];
    [op setCompletionTarget:self
                   selector:@selector(searchOperationDidComplete:)];
    [[NSOperationQueue defaultQueue]
    		replaceOperation:self.currentSearchOperation
               withOperation:op];
    self.currentSearchOperation = op;
    return NO;
}</pre>
<p>The full source code including unit tests, and some additional categories for making operation queue life easier, can be <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/08/Futures.zip">downloaded here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/08/19/future-cocoa-operation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rewriting a Public Cocoa Touch API</title>
		<link>http://blog.jayway.com/2010/05/25/rewriting-a-public-cocoa-touch-api/</link>
		<comments>http://blog.jayway.com/2010/05/25/rewriting-a-public-cocoa-touch-api/#comments</comments>
		<pubDate>Tue, 25 May 2010 14:58:07 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[cocoa touch]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[ipad]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5638</guid>
		<description><![CDATA[Cocoa Touch added API for presenting a view controller in a popup bubble in iPhone OS 3.2, the responsible class is named UIPopoverController. One would guess that this new class is a subclass of UIViewController, just like UINavigationController is, but that is not the case. One would also guess that in functionality many ideas for [...]]]></description>
			<content:encoded><![CDATA[<p>Cocoa Touch added API for presenting a view controller in a popup bubble in iPhone OS 3.2, the responsible class is named <code>UIPopoverController</code>. One would guess that this new class is a subclass of <code>UIViewController</code>, just like <code>UINavigationController</code> is, but that is not the case. One would also guess that in functionality many ideas for displaying a view controller as modal controller would have been moved over to displaying a view controller as a popover controller, but that is not the case either.</p>
<h3>Modal View Controllers are Easy</h3>
<p>Displaying a modal view controller is quite straight forward as this small example shows:</p>
<pre class="brush:objc">-(void)showDetails:(CWDetails*)details {
  UIViewController* vc = [[CWDetailsViewController alloc] initWithDetails:details];
  [self presentModalViewController:vc animated:YES];
  [vc release];
}</pre>
<h3>Popover View Controllers Can be Complex</h3>
<p>Displaying the same details view controller in a popover on iPad is not quite as straight forward:</p>
<pre class="brush:objc">-(void)showDetails:(CWDetails*)details fromBarButtonItem:(UIBarButtonItem*)item {
  UIViewController* vc = [[CWDetailsViewController alloc] initWithDetails:details];
  self.popoverController = [[[UIPopoverController alloc]
                                  initWithContentViewController:vc] autorelease];
  self.popoverController.delegate = self;
  [self.popoverController presentPopoverFromBarButtonItem:item
                                 permittedArrowDirections:UIPopoverArrowDirectionAny
                                                 animated:YES];
  [vc release];
}

-(void)popoverControllerDidDismissPopover:(UIPopoverController*)popoverController {
  self.popoverController = nil;
}</pre>
<p>As you see presenting a popover requires an extra object instance, this instance is not automatically retained while presenting the popover, like a modal view controller is, so the instance must be saved somewhere. In this example I saved the instance as a property. Notice that I also register as a delegate for the popover in order to remove this instance when the popover is dismissed. Here is another detail that is not obvious; this delegate callback is <strong>only</strong> called if user action dismisses the popover, not if you programmatically dismiss the popover. In the end using popovers quite quickly introduces a lot of code, and also coupling between view controllers for no other reason but to manage the popover instance.</p>
<p>Would it not be nice if you could instead do like this, and be done with it:</p>
<pre class="brush:objc">-(void)showDetails:(CWDetails*)details fromBarButtonItem:(UIBarButtonItem*)item {
  UIViewController* vc = [[CWDetailsViewController alloc] initWithDetails:details];
  [self presentPopoverViewController:vc fromBarButtonItem:item animated:YES];
  [vc release];
}</pre>
<p>In fact what we want is to have these methods added to the public API of <code>UIViewController</code>:</p>
<pre class="brush:objc">@interface UIViewController (CWPopover)

@property (nonatomic, retain, readonly) NSSet* visiblePopoverControllers;

-(void)presentPopoverViewController:(UIViewController*)controller
                  fromBarButtonItem:(UIBarButtonItem *)item
                           animated:(BOOL)animated;
-(void)presentPopoverViewController:(UIViewController*)controller
                           fromView:(UIView *)view
                           animated:(BOOL)animated;

-(void)dismissPopoverController:(UIViewController*)controller animated:(BOOL)animated;
-(void)dismissAllPopoverControllersAnimated:(BOOL)animated;

-(void)setContentSize:(CGSize)size forViewInPopoverAnimated:(BOOL)animated;

@end
</pre>
<h3>But That Requires Rewriting Existing Classes?</h3>
<p>Yes it does, in an ideal world we want new methods and properties on the existing <code>UIViewController</code> class, and all subclasses, just as if Apple had put them there. This can easily be done thanks to the dynamic nature of Objective-C.</p>
<p>The view controller that is going to present other view controllers in a  popover needs to have access to all <code>UIPopoverController</code> instances currently visible. The view controllers that are going to be presented in a popover need to have access to their container <code>UIPopoverController</code>, and for consistency with modal view controller its parent view controller. </p>
<p>Categories can only add and replace methods on an existing class, not modify instance variables. So we need to store this information in another way. I choose to tuck them away in a helper class called <code>CWViewControllerPopoverHelper</code>. With this small interface:</p>
<pre class="brush:objc">@interface CWViewControllerPopoverHelper : NSObject {
@private
    UIViewController* parentViewController;
    UIPopoverController* containerPopoverController;
    NSMutableSet* visiblePopoverControllers;
}
@property (nonatomic, assign) UIViewController* parentViewController;
@property (nonatomic, assign) UIPopoverController* containerPopoverController;
@property (nonatomic, retain) NSMutableSet* visiblePopoverControllers;

@end</pre>
<p>The implementation is just synthesized properties, so no need to duplicate that one here.</p>
<p>So now all we do is to stuff one instance of <code>CWViewControllerPopoverHelper</code> into a global map using the <code>UIViewController</code> as key for each view controller that needs these extra <em>instance information</em>.</p>
<h3>Fetching the Popover Helper</h3>
<p>Let's implement a helper method that lazily creates a <code>CWViewControllerPopoverHelper</code> instance and puts it into the global map when needed. This way any view controller that do not need to support popovers will never be bothered, and those who do manage popovers gets one instance with no fuzz:</p>
<pre class="brush:objc">static NSMutableDictionary* popoverHelpers = nil;

-(CWViewControllerPopoverHelper*)popoverHelper;
{
    NSValue* key = [NSValue valueWithPointer:self];
    if (popoverHelpers == nil) {
        popoverHelpers = [[NSMutableDictionary alloc] initWithCapacity:16];
    }
    CWViewControllerPopoverHelper* helper = [popoverHelpers objectForKey:key];
    if (helper == nil) {
        helper = [[[CWViewControllerPopoverHelper alloc] init] autorelease];
        [popoverHelpers setObject:helper forKey:key];
    }
    return helper;
}</pre>
<h3>Proper Memory Management</h3>
<p>There is one problem with storing the extra information in a global map; no view controller would ever be released from memory, since the map will hold on to the references. No problem, lets not use the actual view controller instance as a key, but a <code>NSValue</code> with the pointer to the instance. This solves the problem of releasing objects, but also means that the map will contain dangling pointers to released objects. We need to remove the dangling pointers whenever a <code>UIViewController</code> is deallocated.</p>
<p>Subclassing is not an option, since it would defeat our purpose of requiring the public API. It turns out we can replace the <code>-[UIViewController dealloc]</code> method with our own, and still call the original implementation. Each class and category that is loaded into the Objective-C run-time will call their own method <code>+[? load]</code> method, it is the public hook for further modifying a class or category before use. We want to use this hook to replace the default deallocation method with our own:</p>
<pre class="brush:objc">+(void)load;
{
    Method m1 = class_getInstanceMethod(self, @selector(dealloc));
    Method m2 = class_getInstanceMethod(self, @selector(cwPopoverDealloc));
    method_exchangeImplementations(m1, m2);
    m1 = class_getInstanceMethod(self, @selector(parentViewController));
    m2 = class_getInstanceMethod(self, @selector(cwPopoverParentViewController));
    method_exchangeImplementations(m1, m2);
}</pre>
<p>As a bonus we also replace <code>-[UIViewController parentViewController]</code>, to return the parent as would be expected for anyone who has ever presented a modal view controller. The implementations of our overrides are just as short and sweet:</p>
<pre class="brush:objc">-(void)cwPopoverDealloc;
{
    [self dismissAllPopoverControllersAnimated:NO];
    NSValue* key = [NSValue valueWithPointer:self];
    [popoverHelpers removeObjectForKey:key];
    [self cwPopoverDealloc];
}

-(UIViewController*)cwPopoverParentViewController;
{
    UIViewController* parent = [self popoverHelper].parentViewController;
    if (parent == nil) {
        parent = [self cwPopoverParentViewController];
    }
    return parent;
}</pre>
<h3>Wrapping Up</h3>
<p>From here on it is just a tedious work to implement all 50 more lines of code needed to actually present the popovers, the first method as an example:</p>
<pre class="brush:objc">-(void)presentPopoverViewController:(UIViewController*)controller
                  fromBarButtonItem:(UIBarButtonItem *)item
                           animated:(BOOL)animated;
{
    UIPopoverController* pc = [[[UIPopoverController alloc]
                                initWithContentViewController:controller] autorelease];
	[self addPopoverViewController:pc passthroughViews:views];
    [pc presentPopoverFromBarButtonItem:item
               permittedArrowDirections:UIPopoverArrowDirectionAny
                               animated:animated];
}</pre>
<p>The rest of the implementation, and a few other nice to have methods can be <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/05/UIViewController+CWPopover.zip'>downloaded here</a>.</p>
<h3>Conclusions</h3>
<p>The dynamic nature of Objective-C means that you can rewrite any existing API to suit your needs, without having access to the original source code. Sometimes just to add a new utility function where it belongs; a <em>"sort by first name"</em> method should probably be added to the actual <em>people collection</em> class, not as a spurious utility class.</p>
<p>Or as shown in this example to make a public API more convenient to use.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/05/25/rewriting-a-public-cocoa-touch-api/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Performing any Selector on the Main Thread</title>
		<link>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/</link>
		<comments>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 14:57:48 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[cocoa touch]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5209</guid>
		<description><![CDATA[Many UI frameworks, including AppKit for Mac OS X and UIKit for iPhone OS, require that all methods to UI components are sent on the main UI thread. Cocoa and Cocoa Touch make this quite easy by providing for example -[NSObject performSelectorOnMainThread:withObject:waitUntilDone:] in Foundation. Making updating the text for a text field a snap: [someTextField [...]]]></description>
			<content:encoded><![CDATA[<p>Many UI frameworks, including AppKit for Mac OS X and UIKit for iPhone OS, require that all methods to UI components are sent on the main UI thread. Cocoa and Cocoa Touch make this quite easy by providing for example <code>-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]</code> in Foundation. Making updating the text for a text field a snap:</p>
<pre class="brush:objc">[someTextField performSelectorOnMainThread:@selector(setText:)
                              	withObject:@"A new text"
                             waitUntilDone:YES];</pre>
<h3>But not everything is an object</h3>
<p>Since Objective-C is a superset of C, there are still all the types from C available. Such as all the primitives, including enums, and more complex struct types. Cocoa Touch is pragmatic and will use the most proper type for the use-case, not forcing everything into a square OOP hole.</p>
<p>This makes it quite hard to call for example <code>-[UIView setHidden:]</code>, that takes a single <code>BOOL</code> argument. Same for <code>-[UIView setFrame:]</code>, that takes a single <code>CGRect</code> struct argument, that in turn consists of one <code>CGPoint</code> and one <code>CGSize</code> struct.</p>
<p>Every type imaginable in C can be bundled in an <code>NSValue</code> instance. So we could bundle up the <code>BOOL</code> primitive, or the <code>CGRect</code> struct in a <code>NSValue</code> object. Then pass that object to the main thread, where it is unbundled and passed to the desired method. Quite cumbersome as it requires us to bundle, and unbundle types manually, and implement at least one extra method.</p>
<h3>There must be an easier way</h3>
<p>It turns out that <code>NSInvocation</code> can also handle any imaginable C type, or else it would not be able to invoke any imaginable Objective-C method. Making a <code>NSInvocation</code> invoke its method on the main thread is easy enough. Just add a category to the <code>NSInvocation</code> class, with a new method like this:</p>
<pre class="brush:objc">-(void)invokeOnMainThreadWaitUntilDone:(BOOL)wait;
{
  [self performSelectorOnMainThread:@selector(invoke)
                         withObject:nil
                      waitUntilDone:wait];
}</pre>
<p>So now all you need to do is to create a <code>NSInvocation</code> object, fill it in with the primitive or struct types, and invoke it on the main thread. But creating and setting up a <code>NSInvocation</code> object is also a bit on the boring side...</p>
<h3>There must be an even easier way!</h3>
<p>We could use variable argument lists from plain old C. Too bad that they are untyped?<br />
No despair, we know the target object for our invocation, and we know what method to call. So we have what we need to fetch the <code>NSMethodSignature</code> object for the call, that contains all the type information we need to safely process the <code>va_list</code>.</p>
<p>Our target machine is a Mac running 32- or 64-bit Intel CPU, or an iPhone OS device with a 32 bit ARM CPU. Turns out that on both platforms <code>va_list</code> is simply a <code>void*</code> pointer, to the stack frame. Even better <code>va_start()</code> will always flush any argument passed into the register on the stack frame. So we can skip most of the boring argument handling, by treating the arguments like a byte buffer, only advancing and aligning the buffer according to the information in the <code>NSMethodSignature</code> object.</p>
<p>A convenience method for creating a <code>NSInvocation</code> object for a particular target, selector, and list of variable arguments, would turn out like this:</p>
<pre class="brush:objc">+(NSInvocation*)invocationWithTarget:(id)target
                            selector:(SEL)aSelector
                     retainArguments:(BOOL)retainArguments, ...;
{
  va_list ap;
  va_start(ap, retainArguments);
  char* args = (char*)ap;
  NSMethodSignature* signature = [target methodSignatureForSelector:aSelector];
  NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature];
  if (retainArguments) {
    [invocation retainArguments];
  }
  [invocation setTarget:target];
  [invocation setSelector:aSelector];
  for (int index = 2; index < [signature numberOfArguments]; index++) {
    const char *type = [signature getArgumentTypeAtIndex:index];
    NSUInteger size, align;
    NSGetSizeAndAlignment(type, &size, &align);
    NSUInteger mod = (NSUInteger)args % align;
    if (mod != 0) {
      args += (align - mod);
    }
    [invocation setArgument:args atIndex:index];
    args += size;
  }
  va_end(ap);
  return invocation;
}
</pre>
<h3>Conclusion</h3>
<p>And now we can easily call any method on the main UI thread. </p>
<p>An example where a <code>CGRect</code> struct is used to update the UI components frame;</p>
<pre class="brush:objc">// Set new frame of a label.
[[NSInvocation invocationWithTarget:someLabel
                           selector:@selector(setFrame:)
                    retainArguments:NO, CGRectMake(40, 40, 200, 100)]
 invokeOnMainThreadWaitUntilDone:NO];</pre>
<p>A slightly more complex example, where we send a primitive int, and also waits for and fetches the result from the main thread:</p>
<pre class="brush:objc">// Query a UITableView for the number of rows in section 2.
NSInvocation* i = [NSInvocation invocationWithTarget:tableView
                                            selector:@selector(numberOfRowsInSection:)
                                     retainArguments:NO, (NSUInteger)2];
// Block this thread until method has been invoked and result is available.
[i invokeOnMainThreadWaitUntilDone:YES];
NSInteger numberOfRows;
[i getReturnValue:&numberOfRows];</pre>
<p>Download full source code here: <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/03/NSInvocation+CWVariableArguments.zip'>NSInvocation+CWVariableArguments.zip</a></p>
<p><em>Update: Example 2 was not 64-bit compatible as <a href="http://twitter.com/chmod007">David Remahl</a> pointed out to me. Added type cast to fix the error.</em></p>
<p><em>Update 2: A new version with some more features and small bug-fixes to BOOL, float and uint16_t types, plus proper unit tests can be downloaded here: <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/03/CWFoundationAsyncAdditions.zip'>CWFoundationAsyncAdditions.zip</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Continuos Integration for XCode projects</title>
		<link>http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/</link>
		<comments>http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 17:35:59 +0000</pubDate>
		<dc:creator>Christian Hedin</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[hudson]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[xcode]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4624</guid>
		<description><![CDATA[Continuos Integration is the practice of integrating changes from many people as often as possible. Instead of merging changes once a month and spending time handling merge errors you try integrate every day, perhaps even every hour. Each integration is built and tested on a server. If there are build errors or test failures, you [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://martinfowler.com/articles/continuousIntegration.html" title="Continuous Integration">Continuos Integration</a> is the practice of integrating changes from many people as often as possible. Instead of merging changes once a month and spending time handling merge errors you try integrate every day, perhaps even every hour. Each integration is built and tested on a server. If there are build errors or test failures, you and your team will be notified right away.
</p>
<p>
This is the second part of the blog post I wrote about <a href="http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/">TDD in XCode</a>. Make sure you've followed that tutorial before continuing here, or at least have a project of your own with OCUnit tests ready.
</p>
<p>
The server which we'll use is called <a href="https://hudson.dev.java.net/" title="Hudson">Hudson</a> and is very popular in the Java community. It does not readily support XCode projects but it does allow shell commands, so we'll use that to make our Calculator project compatible. We also want to fetch new versions of the source code as soon as it's checked in. We'll be a bit fancy and use <a href="http://git-scm.com/" title="Git - Fast Version Control System">Git</a> as source control software.	Here's a summary of what we want to do:
</p>
<ol>
<li>Download and install the Hudson continuos integration server</li>
<li>Download, install and setup the Git source control software as well as the Git plugin for Hudson</li>
<li>Download and install a script that converts OCUnit test results to JUnit format</li>
<li>Setup a new job in Hudson that checks out our XCode project and builds and tests it</li>
<li>Set up a notification and try it out</li>
</ol>
<h2>Downloading and Installing Hudson</h2>
<p>
In order to keep the instructions in this tutorial simple, we will have the source code repository and the build server itself on localhost. In real life you'll probably want to setup a dedicated machine.</p>
<p>Head over to the <a href="https://hudson.dev.java.net/" title="Hudson">Hudson web site</a> and download your copy of the server. Follow their included installation instructions, it's quite simple. Once you have Hudson up and running you can visit <a href="http://localhots:8080">http://localhost:8080</a> to see the welcome screen. By the way, when you're ready to install Hudson on a real remote server I recommend running it as a Servlet inside <a href="http://tomcat.apache.org/" title="Apache Tomcat - Welcome!">Apache Tomcat</a> instead.
</p>
<h2>Downloading and Setting Up Git</h2>
<p>Next we want to install Git. There are several ways to install it. The simplest might be to use <a href="http://code.google.com/p/git-osx-installer/">the OS X installer</a>, but I personally prefer <a href="http://www.macports.org/" title="The MacPorts Project">MacPorts</a>. Either way, go ahead and install it and make sure that you can use the "git" command from Terminal.app when you're done.
</p>
<p>
In the Terminal, change directory to your XCode project folder and type:</p>
<pre class="brush:bash">
		git init
	</pre>
<p>You now have a working source code repository in your project folder. Neat. Before you continue create a text file called <em>.gitignore</em> and let it contain:</p>
<pre class="brush:plain">
		build/*
		*.pbxuser
		*.mode1v3
		.DS_Store
		test-reports/*
	</pre>
<p>	That's a listing of the files and folders that should not be version controlled, since they are temporary or just used for XCode. Feel free to add any other files that you think only should be present locally. Now add all files (that aren't ignored) using:</p>
<pre class="brush:bash">
		git add *
	</pre>
<p>	and finally commit them to a first version using:</p>
<pre class="brush:bash">
		git commit -m "Initial import"
	</pre>
</p>
<h2>Fetching the Script</h2>
<p>
We need to fetch one more thing, <a href="http://github.com/ciryon/OCUnit2JUnit/blob/master/ocunit2junit.rb">ocunit2junit.rb</a>, which is a little Ruby script that I wrote. Since you now have git, you can also download it using git (or <em>clone the repo</em>, which is the correct term). Change directory to /tmp and then type like this:</p>
<pre class="brush:bash">git clone git://github.com/ciryon/OCUnit2JUnit.git</pre>
<p>Copy the script from /tmp/OCUnit2JUnit/ anywhere, like to /usr/local/bin/. Make sure it's executable by typing <em>chmod +x ocunit2junit.rb</em>.</p>
<p>The script will parse output from xcodebuild (the console command for building your XCode project) and look for output from OCUnit. The test results (success, failure, time passed etc) will be saved in the "test-reports" folder in the same XML format that JUnit uses. This also happens to be a format that Hudson understands.
</p>
<h2>Setting Up Hudson</h2>
<p>
Now head back to your Hudson welcome screen. Select <em>Manage Hudson</em>, <em>Manage plugins</em> and check "Hudson GIT plugin" under <em>Available</em>. Hudson will automatically download and install the plugin. Afterwards just restart Hudson.
</p>
<p>
We're ready to create a job in Hudson for our project. From the main screen select "New job", Build a free-style software project and call it "Calculator". There are some settings which you should fill in:</p>
<ul>
<li>
			Select to use git as source code management tool. The URL should be the file path to your project, like:
<pre class="brush:bash">/Users/youruser/XCodeProjects/Calculator/</pre>
</li>
<li>
			Select to poll SCM with Schedule:
<pre class="brush:bash">* * * * *</pre>
<p>			That means it'll check every minute if there are changes. If you want to check less often, do that.
		</li>
<li>
			Add new build step and select to execute shell. Use this command (make sure to point to the version of the iPhone SDK you want to use):</p>
<pre class="brush:plain">xcodebuild -target "UnitTests" -sdk /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.2.sdk/ -configuration "Debug" | /usr/local/bin/ocunit2junit.rb</pre>
</li>
<li>
			Select to also publish a JUnit test result report and the Test report XMLs reside at
<pre class="brush:plain">test-reports/*.xml</pre>
</li>
</ul>
<h2>Trying it out</h2>
<p>This is the moment of truth. Try to change your CalculatorTest.m so that one of the test cases fail. Type:</p>
<pre class="brush:bash">
	git -a commit CalculatorTest.m "Broke the test, on purpose"
</pre>
<p>and see what happens. If all goes well, and you have entered everything correctly,  Hudson should automatically notice there's a new version available, build it and try to run the test suite. Check the results and how it reports the test failure. Nice, eh? Fix the error and commit the test class again to see how Hudson reacts.
</p>
<p>
There are many settings, plugins and cool things to try out in Hudson. Go into Manage Hudson-> Configure system and setup your email settings, to allow Hudson to send mail. Then go back to configure your Calculator job and at the bottom select E-mail Notification. Enter your own email address and see how it works after you commits a file that breaks the build. If you don't want a mail, you can get an instant message, or perhaps have the server play a loud annoying sound? Everyone in your team should be aware of when a build fails, so it can be fixed right away. This is one of the great advantages of having a continuos integration server.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>Test Driven Development in XCode</title>
		<link>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/</link>
		<comments>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 08:35:26 +0000</pubDate>
		<dc:creator>Christian Hedin</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4301</guid>
		<description><![CDATA[Test Driven Development, or TDD for short, is a simple software development practice where unit tests, small focused test cases, drive the development forward. This is most easily explained by the Three Rules of TDD that dictate the following: You are not allowed to write any production code unless it is to make a failing [...]]]></description>
			<content:encoded><![CDATA[<p>
        <a href="http://en.wikipedia.org/wiki/Test-driven_development" title="Test-driven development - Wikipedia, the free encyclopedia">Test Driven Development</a>, or TDD for short, is a simple software development practice where unit tests, small focused test cases, drive the development forward. This is most easily explained by the <a href="http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd" title="TheThreeRulesOfTdd">Three Rules of TDD</a> that dictate the following:</p>
<ol>
<li>You are not allowed to write any production code unless it is to make a failing unit test pass.</li>
<li>You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.</li>
<li>You are not allowed to write any more production code than is sufficient to pass the one failing unit test.</li>
</ol>
<p>That means that test cases are written before any production code. Not all tests are written up front, it's rather that a small test is written, then a small piece of production code is written that only allows that test to pass. This is repeated in <a href="http://www.agiledata.org/essays/tdd.html">many small iterations</a>: test, fail, code, pass, test, fail, code, pass...<br/><br />
Many people consider TDD to encourage clean code, simple architectures and a stable system that's actually testable. Plus, it's also fun! We've <a href="/tag/tdd/">previously written</a> about various aspects of TDD, but in this tutorial we'll focus on how it works for XCode projects, where you write apps for Mac and iPhone. We will create a simple XCode project, do some special configuration steps and then demonstrate how TDD can be used to write your app. We're going to use <a href="http://www.sente.ch/software/ocunit/">OCUnit</a> and its framework SenTestingKit, which nowadays is included with Apple's XCode tools.
</p>
<h2>Creating the Calculator project</h2>
<p>
Let's start by creating a new project in XCode. You can pick any template, since we aren't going to touch the generated code. I picked a Window-based iPhone project. Name the project <em>Calculator</em>. Select New Target from the Project menu. Under Cocoa select Unit test Bundle. Call it <em>UnitTests</em> (I've had problems with space in the target name so avoid that) and add it to the project. We now need to change some small settings for this target. Select the UnitTests target and hit Command-I for Info. Select the Build tab and locate <em>Other Linker Flags</em>. Replace <em>Cocoa</em> with <em>Foundation</em>. Also remove the entry for <em>GCC_PREFIX_HEADER</em>.
</p>
<p>
Now it's time to create your test suite. Create a new group in your project and call it "Test Classes". Add a new File to this group and make sure it's a Cocoa->Objective-C test case class. Name it <em>CalculatorTest.m</em>. Uncheck "Also create CalculatorTest.h" since we don't need a header file. Don't add it to the Calculator target, but check it to be included in UnitTests. Open CalculatorTest.m file and above the @implementation declaration add:</p>
<pre class="brush:objc">#import &lt;SenTestingKit/SenTestingKit.h&gt;
#import "Calculator.h"
@interface CalculatorTest : SenTestCase
{

}
@end</pre>
<p>This is just because we don't want a rather empty header file. All your test classes will look like this.</p>
<p>Following TDD, we should build right away.  First make sure that the active target is "UnitTets" and then press the "Build" button. This will not only do a normal build, but also perform some shell script magic and actually execute the  unit tests. Now the build fails of course, since Calculator.h can't be found.</p>
<p>So let's add a file which represents production code. Create a new empty Cocoa Touch Objective-C class called Calculator.m (also create the .h file), this is the class that we want to test. Don't forget to check that they should be included in both your targets. Notice that we mix Cocoa and Cocoa Touch, that's is fine - all code is executed on your Mac. Build again, and this time you'll see in the build log that everything built and the test suite was executed, but contained 0 test cases. Let's remedy that.
</p>
<h2>Writing test cases</h2>
<p>
Next we want to write our first test case. Open up CalculatorTest.m and add the following method:</p>
<pre class="brush:objc">-(void)testAdd
{
        Calculator* calculator = [[Calculator alloc] init];
        int result = [calculator add:5 to:6];
}</pre>
<p>All methods that start with "test" will be recognized as being a test case, and automatically run when building the target. Try and build and you'll unsurprisingly get the erro "unrecognized selector sent to instance...". That's all good. Let's add the add method to our Calculator class. In Calculator.h add:</p>
<pre class="brush:objc">-(int)add:(int)a to:(int)b;</pre>
<p>Then in Calculator.m add:</p>
<pre class="brush:objc">-(int)add:(int)a to:(int)b
{
        return 0;
}</pre>
<p>That should be enough to let it compile and run, right? Try it out! You'll see that it indeed build and executes the tests.
</p>
<p>
        Now we change the test so that it actually checks that we get the expected value back. We want to "assert" that the returned value is what we expected. Change the test case to look like this:</p>
<pre class="brush:objc">-(void)testAdd
{
        Calculator* calculator = [[Calculator alloc] init];
        int expected = 11;
        int result = [calculator add:5 to:6];
        STAssertEquals(expected, result,
                @"We expected %d, but it was %d",expected,result);
}</pre>
<p>Build and you see that the test runs and fails since our calculator always returns 0 regardless of the input. Change the production code so that it returns a+b and rerun the test. Nice, we have a successful build and our test works! Notice the fast cycle of test, code, fix, rerun. The point of TDD is to write tests and production code in small iterations so that you always have something stable (= the tests pass). If you follow the rules of TDD you'll have a growing amount of test cases and you'll right away know when something breaks.
</p>
<p>
Let's write one more test. Now we want to add the functionality to allow one number to be divided by another. Start up like before with a new test case like this:</p>
<pre class="brush:objc">-(void)testDivide
{
        Calculator* calculator = [[Calculator alloc] init];
        float expected = 2.5;
        int result = [calculator divide:5 by:2];
        STAssertEquals(expected, result,
                @"We expected %d, but it was %d",expected,result);
}</pre>
<p>You see, this time we expect to get back a float. Add the corresponding divide method to Calculator.h and Calculator.m. If you need help see the full code listing at the end of this article. You might notice that just returning a/b gives you 2.0. Type cast the return value to (float)a/b and you'll be fine. Go ahead when you got it working.
</p>
<p>
What happens if you try to divide something with zero? Well, why not add a test case for this scenario? If you're into maths you know that the result of this operation is undefined. How do you expect something to be undefined? This is tricky. <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  Start off by just expecting any number and see what you get back. As you see, the float value "inf" is returned. It seems like Objective-C treats the zero as "a value approaching zero" and that will indeed result in infinity in a division. But, hey, that might not be what we want our calculator to do. Let's change the test case to expect an exception to be raised instead:</p>
<pre class="brush:objc">-(void)testDivideByZero
{
        Calculator* calculator = [[Calculator alloc] init];
        STAssertThrows([calculator divide:5 by:0],
                @"We expected an exception to be raised when dividing by 0");
}</pre>
<p>Build and notice the error message when no exception was raised. Now change the production code to something like this:</p>
<pre class="brush:objc">-(float)divide:(int)a by:(int)b
{
        float result =  (float)a/b;
        if (result==INFINITY) {
                [NSException raise:@"Cannot divide by zero!"
                            format:@"Not possible to divide %d with %d", a,b];
        }
        return result;
}</pre>
<p>Rerun and smile as the test passes! There are many different variants of asserts you can do with SenTestingKit. Compare objects with STAssertEqualObjects. STAssertTrue to check that a returned boolean is true. Open up SentTestCase_Macros.h if you want to see what you can play around with. By the way. You might have tried using NSLog in your test cases (just to experiment). This is nothing you would do in real life, as you want all necessary information in the fail message and output nothing if the test passes. Anyway, since the tests are actually run using a separate shell script for the UnitTest target you won't see the log in your console as usual. Instead check the build log and click the "text" icon to the right for the "Run test suite" step.
</p>
<h2>Wrapping up</h2>
<p>
Finally, if you look at your test class you might notice that we're allocating a new Calculator for every test case, and we never release them. That's no good. Luckily there are setUp and tearDown methods that will be launched automatically before and after each test case. Change your implementation to look like this (this is the final listing):</p>
<pre class="brush:objc">#import &lt;SenTestingKit/SenTestingKit.h&gt;
#import "Calculator.h"
@interface CalculatorTest : SenTestCase
{
        Calculator* calculator;
}
@end

@implementation CalculatorTest

- (void) setUp
{
        calculator = [[Calculator alloc] init];
}

-(void)tearDown
{
        [calculator release];
}

-(void)testAdd
{
        int expected = 11;
        int result = [calculator add:5 to:6];
        STAssertEquals(expected, result,
                @"We expected %d, but it was %d",expected,result);
}

-(void)testDivide
{
        float expected = 2.5;
        float result = [calculator divide:5 by:2];
        STAssertEquals(expected, result,
                @"We expected %f, but it was %f",expected,result);
}

-(void)testDivideByZero
{
        STAssertThrows([calculator divide:5 by:0],
                @"We expected an exception to be raised when dividing by 0");
}
@end</pre>
</p>
<p>
For completeness, here's the listing for Calculator.h:</p>
<pre class="brush:objc">#import <Foundation/Foundation.h>

@interface Calculator : NSObject {

}

-(int)add:(int)a to:(int)b;
-(float)divide:(int)a by:(int)b;

@end</pre>
<p>and for Calculator.m:</p>
<pre class="brush:objc">#import "Calculator.h"

@implementation Calculator

-(int)add:(int)a to:(int)b
{
        return a+b;
}

-(float)divide:(int)a by:(int)b
{
        float result =  (float)a/b;
        if (result==INFINITY) {
                [NSException raise:@"Cannot divide by zero!"
                            format:@"Not possible to divide %d with %d", a,b];
        }
        return result;
}

@end</pre>
<p>Next blog post we'll see how to automate the running of test cases on a build server called Hudson!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Google Translate and iPhone apps</title>
		<link>http://blog.jayway.com/2010/01/11/google-translate-and-iphone-apps/</link>
		<comments>http://blog.jayway.com/2010/01/11/google-translate-and-iphone-apps/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 09:22:17 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[localization]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4251</guid>
		<description><![CDATA[The Cocoa and Cocoa Touch frameworks has a really nice function for acquiring a localized string NSLocalizedString(). Just pass in a key and you are done, for strings that are known at least. Sometimes you are getting unknown strings from a data source not under your control, strings representing just a fraction of the text [...]]]></description>
			<content:encoded><![CDATA[<p>The Cocoa and Cocoa Touch frameworks has a really nice function for acquiring a localized string <code>NSLocalizedString()</code>. Just pass in a key and you are done, for strings that are known at least. Sometimes you are getting unknown strings from a data source not under your control, strings representing just a fraction of the text in your UI. Leaving this text in it's source language looks weird, and skipping translation all together just feel wrong.</p>
<h3>Google Translate to the rescue</h3>
<p>Turns out that Google Translate has a nice AJAX API, feed it a URL request and get a JSON response. Admittedly the translations are not always perfect, even quite humorous at times, but good enough if you provide the user a warning.</p>
<p>So let us create a sibling to <code>NSLocalizedString()</code> called <code>CWTranslatedString()</code>. It should take two arguments; the string to translate, and the source language ISO code. We should also be able to get the users currently selected language, that will be used as the destination language when translating. So this is our header:</p>
<pre class="brush:c">NSString* CWCurrentLanguageIdentifier();
NSString* CWTranslatedString(NSString* string, NSString* sourceLanguageIdentifier);</pre>
<p>Currently your iPhone application must be terminated in order for the user to change the language. And even when Apple adds multitasking for third-party apps we can assume the user do not go about and switch languages too often, so we let <code>CWCurrentLanguageIdentifier()</code> cache the language code:</p>
<pre class="brush:c">NSString* CWCurrentLanguageIdentifier() {
    static NSString* currentLanguage = nil;
    if (currentLanguage == nil) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSArray* languages = [defaults objectForKey:@"AppleLanguages"];
        currentLanguage = [[languages objectAtIndex:0] retain];
    }
    return currentLanguage;
}</pre>
<p>Now for the <code>CWTranslatedString()</code> function. The JSON response from Google Translate is well formatted with no line breaks, so let's not bother with a proper JSON-parser. We can use a simple <code>NSScanner</code>, and just return the source string for any unexpected result. We also short circuit and return the source string if the source and dest language as equal.</p>
<pre class="brush:c">NSString* CWTranslatedString(NSString* string, NSString* sourceLanguageIdentifier) {
    static NSString* queryURL = @"http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%@&langpair=%@%%7C%@";
    if (sourceLanguageIdentifier == nil) {
        sourceLanguageIdentifier = @"en";
    }
    if ([sourceLanguageIdentifier isEqual:CWCurrentLanguageIdentifier()] || string == nil) {
        return string;
    }
    NSString* escapedString = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString* query = [NSString stringWithFormat:queryURL,
                       escapedString, sourceLanguageIdentifier, CWCurrentLanguageIdentifier()];
    NSString* response = [NSString stringWithContentsOfURL:[NSURL URLWithString:query]
                                                  encoding:NSUTF8StringEncoding error:NULL];
    if (response == nil) {
        return string;
    }
    NSScanner* scanner = [NSScanner scannerWithString:response];
    if (![scanner scanUpToString:@"\"translatedText\":\"" intoString:NULL]) {
        return string;
    }
    if (![scanner scanString:@"\"translatedText\":\"" intoString:NULL]) {
        return string;
    }
    NSString* result = nil;
    if (![scanner scanUpToString:@"\"}" intoString:&result]) {
        return string;
    }
    return result;
}</pre>
<p>And that is it. Not perfect, but nice to have.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/11/google-translate-and-iphone-apps/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Add some polish to iPhone app start up</title>
		<link>http://blog.jayway.com/2009/06/29/add-some-polish-to-iphone-app-start-up/</link>
		<comments>http://blog.jayway.com/2009/06/29/add-some-polish-to-iphone-app-start-up/#comments</comments>
		<pubDate>Mon, 29 Jun 2009 07:13:06 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1885</guid>
		<description><![CDATA[First impressions last, and the very first impression your users have of your iPhone application is the start up. First step is to have a nice Default.png, but not many words spilled on that one, it is well covered in Apple's documentation. Creating a perfect Default.png is impossible, especially if you have different setup of [...]]]></description>
			<content:encoded><![CDATA[<p>First impressions last, and the very first impression your users have of your iPhone application is the start up. First step is to have a nice <code>Default.png</code>, but not many words spilled on that one, it is well covered in Apple's documentation.</p>
<p>Creating a perfect <code>Default.png</code> is impossible, especially if you have different setup of navigation and tab bars in different parts of your app. And even harder to adjust for the different sizes of the status bar. With the advent of tethering the size of the status bar is even more sure to be random at startup. This adds to a small jerk, or ugly jump of the user interface at start up.</p>
<h3>Create a smooth startup</h3>
<p>The easiest way to counter this small jerk is to let your user interface fade in. It is pleasing to the eye, and easy to do. So easy that this blog post pretty much ends after a small code block you can cut&paste into any of your projects.</p>
<p>If you create your UI using Interface Builder, or create it in code, you still have an implementation of <code>applicationDidFinishLaunching:</code> that ends like this:</p>
<pre class="objc">-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>applicationDidFinishLaunching:<span style="color: #002200;">&#40;</span>UIApplication*<span style="color: #002200;">&#41;</span>application;
<span style="color: #002200;">&#123;</span>
<span style="color: #ff0000;">// ...more code...</span>
  <span style="color: #002200;">&#91;</span>window makeKeyAndVisible<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>This is where we will add our own code that will slide in a new view, above the root view, mimicking the <code>Default.png</code> look. This view is then quickly faded out and removed, creating the appearance of fading in our real user interface.</p>
<pre class="objc">-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>applicationDidFinishLaunching:<span style="color: #002200;">&#40;</span>UIApplication*<span style="color: #002200;">&#41;</span>application;
<span style="color: #002200;">&#123;</span>
<span style="color: #ff0000;">// ...more code...</span>
  UIImage* backImage = <span style="color: #002200;">&#91;</span>UIImage imageNamed:@<span style="color: #666666;">&quot;Default.png&quot;</span><span style="color: #002200;">&#93;</span>;
  UIView* backView = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIImageView alloc<span style="color: #002200;">&#93;</span> initWithImage:backImage<span style="color: #002200;">&#93;</span>;
  backView.frame = window.bounds;
  <span style="color: #002200;">&#91;</span>window addSubview:backView<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>UIView beginAnimations:@<span style="color: #666666;">&quot;CWFadeIn&quot;</span> context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>backView<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>UIView setAnimationDelegate:self<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>UIView setAnimationDidStopSelector:
      <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>animationDidStop:finished:context:<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>UIView setAnimationDuration:<span style="color: #0000dd;">0</span>.5f<span style="color: #002200;">&#93;</span>;
  backView.alpha = <span style="color: #0000dd;">0</span>;
  <span style="color: #002200;">&#91;</span>UIView commitAnimations<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>window makeKeyAndVisible<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>animationDidStop:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>*<span style="color: #002200;">&#41;</span>animationID finished:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSNumber.html"><span style="color: #0000ff;">NSNumber</span></a>*<span style="color: #002200;">&#41;</span>finished
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context
<span style="color: #002200;">&#123;</span>
  UIView* backView = <span style="color: #002200;">&#40;</span>UIView*<span style="color: #002200;">&#41;</span>context;
  <span style="color: #002200;">&#91;</span>backView removeFromSuperview<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>backView release<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>And that is it, instant better first impression.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/06/29/add-some-polish-to-iphone-app-start-up/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Queued Background Tasks for Cocoa</title>
		<link>http://blog.jayway.com/2009/05/09/queued-background-tasks-for-cocoa/</link>
		<comments>http://blog.jayway.com/2009/05/09/queued-background-tasks-for-cocoa/#comments</comments>
		<pubDate>Sat, 09 May 2009 12:42:04 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1665</guid>
		<description><![CDATA[The megahertz race is over, and instead we get more execution cores. This means that we as developers must make our applications parallel, in order to take advantage of the new performance. The easiest way to be parallel is to execute tasks in new threads, something that is useful also for lengthy but not resource [...]]]></description>
			<content:encoded><![CDATA[<p>The megahertz race is over, and instead we get more execution cores. This means that we as developers must make our applications parallel, in order to take advantage of the new performance. The easiest way to be parallel is to execute tasks in new threads, something that is useful also for lengthy but not resource intensive tasks such as network access.</p>
<p>Any sane developer avoids premature optimization, so the task we later want to execute in a separate thread is almost always available in our current context. I am sure all Java-developers has seen something like this:</p>
<pre class="java"> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThread+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Thread</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> run<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        OuterClass.<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">someMethod</span><span style="color: #66cc66;">&#40;</span>arg<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>.<span style="color: #006600;">start</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</pre>
<p>And often an anonymous <code>Runnable</code> is involved as well. Executing a task in a separate thread with Cocoa and Cocoa Touch is ridiculously easy given the dynamic nature of Objective-C. This is done with Cocoa with this one-liner:</p>
<pre class="objc"><span style="color: #002200;">&#91;</span>self performSelectorInBackground:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>someMethod:<span style="color: #002200;">&#41;</span> withObject:arg<span style="color: #002200;">&#93;</span>;</pre>
<p>The <code>performSelectorInBackground:withObject:</code> is a companion method for <code>performSelector:withObject:</code>, and will create a new <code>NSThread</code> instance, and execute the specified method there. There are more companions such as <code>performSelectorOnMainThread:withObject:</code> that is used to execute a method on the main UI thread.</p>
<p>This easy access to executing in new threads often can result in code that spawns too many threads. In Cocoa on Mac OS X this is seldom a problem, not for Cocoa Touch applications under development when running in the iPhone simulator either. But on the more resource constrained iPhone and iPod Touch devices this will be a problem. Spawning a dozen background threads to download images will bring the iPhone OS to a staggering mess.</p>
<p><em><strong>Update: </strong>I have removed <code>CWSelectorOperation</code> from this post, since using <code>NSInvocationOperation</code> is preferred.</em></p>
<h3>Operation Queues</h3>
<p>The solution is to use a <code>NSOperationQueue</code>, that as the name implies handles a queue of operations. The max number of concurrent operations can be set, as well as dependencies and priority. The downside is that <code>NSOperationQueue</code> can only handle instances of <code>NSOperation</code>.</p>
<p><code>NSOperation</code> is an abstract class, where you as a developer override the <code>main</code> method to execute your task. In short <code>NSOperation</code> is programatically the equivalent of the Java <code>Runnable</code> interface. It is even worse as Objective-C do not support anonymous classes, so we will be required to actually implement our queued tasks as separate classes.</p>
<p>Not as neat as one would like, and definitely not even very Cocoa-like.</p>
<h3>What is Missing</h3>
<p>As a Cocoa developer I expect that executing a task on background queue, would be just as easy as executing a task on a background thread. The expected needed code is something like this:</p>
<pre class="objc"><span style="color: #002200;">&#91;</span>self performSelectorOnBackgroundQueue:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>someMethod:<span style="color: #002200;">&#41;</span> withObject:arg<span style="color: #002200;">&#93;</span>;</pre>
<p>To make this work we need:</p>
<ol>
<li>A category on <code>NSObject</code> to add <code>performSelectorOnBackgroundQueue:withObject:</code>.</li>
<li><del datetime="2009-05-13T10:47:35+00:00">Implement a concrete subclass of <code>NSOperation</code> to support execution of a selector on any target.</del>Use <code>NSInvocationOperation</code> to perform selector.</li>
<li>A category on <code>NSOperationQueue</code> to add a shared operation queue.</li>
</ol>
<p>This is in the order of how a client developer would see it (most developers will only care for the <code>NSObject</code> category). For us this is the reverse order when implement this functionality.</p>
<h3>A Shared Operation Queue</h3>
<p>Cocoa and Cocoa Touch used many shared instances, for example a shared <code>UIAccelerometer</code> instance, and a shared <code>NSURLCache</code> instance. So this pattern of single point dependency injection is common in Cocoa and works very well. So let us follow suit by introducing an interface like this:</p>
<pre class="objc"><span style="color: #0000ff;">@interface</span> NSOperationQueue <span style="color: #002200;">&#40;</span>CWSharedQueue<span style="color: #002200;">&#41;</span>
+<span style="color: #002200;">&#40;</span>NSOperationQueue*<span style="color: #002200;">&#41;</span>sharedOperationQueue;
+<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>setSharedOperationQueue:<span style="color: #002200;">&#40;</span>NSOperationQueue*<span style="color: #002200;">&#41;</span>operationQueue;
<span style="color: #0000ff;">@end</span></pre>
<p>The shared operation queue will be created lazily if it do not exist, and the client can easily swap it out at startup if needed. The implementation is very small, and a good example of how we should implement class variables with proper memory handling.</p>
<pre class="objc"><span style="color: #0000ff;">@implementation</span> NSOperationQueue <span style="color: #002200;">&#40;</span>CWSharedQueue<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #0000ff;">static</span> NSOperationQueue* cw_sharedOperationQueue = <span style="color: #0000ff;">nil</span>;
&nbsp;
+<span style="color: #002200;">&#40;</span>NSOperationQueue*<span style="color: #002200;">&#41;</span>sharedOperationQueue;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>cw_sharedOperationQueue == <span style="color: #0000ff;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    cw_sharedOperationQueue = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSOperationQueue alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>cw_sharedOperationQueue setMaxConcurrentOperationCount:<span style="color: #0000dd;">3</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> cw_sharedOperationQueue;
<span style="color: #002200;">&#125;</span>
&nbsp;
+<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>setSharedOperationQueue:<span style="color: #002200;">&#40;</span>NSOperationQueue*<span style="color: #002200;">&#41;</span>operationQueue;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>operationQueue != cw_sharedOperationQueue<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>cw_sharedOperationQueue release<span style="color: #002200;">&#93;</span>;
    cw_sharedOperationQueue = <span style="color: #002200;">&#91;</span>operationQueue retain<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3><del datetime="2009-05-13T10:47:35+00:00">Enter <code>CWSelectorOperation</code></del></h3>
<p><em><strong>Update: </strong><code>CWSelectorOperation</code> is no longer needed, our implementation instead uses <code>NSInvocationOperation</code>.</em></p>
<h3>Wrapping up <code>NSObject</code></h3>
<p>And at last we reach the category on <code>NSObject</code>, that is what we initially wanted, and what 95% of all use cases will be limited to.</p>
<pre class="objc"><span style="color: #0000ff;">@interface</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSObject.html"><span style="color: #0000ff;">NSObject</span></a> <span style="color: #002200;">&#40;</span>CWSharedQueue<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSInvocationOperation*<span style="color: #002200;">&#41;</span>performSelectorInBackgroundQueue:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
    withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>arg;
-<span style="color: #002200;">&#40;</span>NSInvocationOperation*<span style="color: #002200;">&#41;</span>performSelectorInBackgroundQueue:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
    withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>arg dependencies:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>dependencies
    priority:<span style="color: #002200;">&#40;</span>NSOperationQueuePriority<span style="color: #002200;">&#41;</span>priority;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>Most <code>performSelector*</code> methods do not have a return value, I have chosen to return the resulting <code> NSInvocationOperation </code> so that it can be used to setup dependencies for future queued operations. I have also added a second method <code>performSelectorInBackgroundQueue:withObject:dependencies:priority:</code> so that such dependencies can easily be setup, as well as prioritisation of operations.</p>
<p>The actual implementation is a simple wrapper around the <code> NSInvocationOperation </code> class, and category on <code>NSOperationQueue</code> that we implemented above:</p>
<pre class="objc"><span style="color: #0000ff;">@implementation</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSObject.html"><span style="color: #0000ff;">NSObject</span></a> <span style="color: #002200;">&#40;</span>CWSharedQueue<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSInvocationOperation*<span style="color: #002200;">&#41;</span>performSelectorInBackgroundQueue:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
    withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>arg;
<span style="color: #002200;">&#123;</span>
  NSInvocationOperation* operation = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSInvocationOperation alloc<span style="color: #002200;">&#93;</span>
      initWithTarget:self selector:aSelector object:arg<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSOperationQueue sharedOperationQueue<span style="color: #002200;">&#93;</span> addOperation:operation<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>operation autorelease<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSInvocationOperation*<span style="color: #002200;">&#41;</span>performSelectorInBackgroundQueue:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
    withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>arg dependencies:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>dependencies
    priority:<span style="color: #002200;">&#40;</span>NSOperationQueuePriority<span style="color: #002200;">&#41;</span>priority;
<span style="color: #002200;">&#123;</span>
  NSInvocationOperation* operation = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSInvocationOperation alloc<span style="color: #002200;">&#93;</span>
      initWithTarget:self selector:aSelector object:arg<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>operation setQueuePriority:priority<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">for</span> <span style="color: #002200;">&#40;</span>NSOperation* dependency in dependencies<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>operation addDependency:dependency<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSOperationQueue sharedOperationQueue<span style="color: #002200;">&#93;</span> addOperation:operation<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>operation autorelease<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>And that is it, if you want to avoid cut and paste of all this code to your own project just <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/05/nsoperationqueuecwsharedqueue.zip'>download the source code here</a>. And happy concurrent hacking.</p>
<p>Download the <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/05/cwselectoroperation.zip'>older source code here</a>, with a concrete subclass of <code>NSOperation</code> called <code>CWSelectorOperation</code>. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/09/queued-background-tasks-for-cocoa/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Regular Expressions and Cocoa</title>
		<link>http://blog.jayway.com/2009/05/06/regular-expressions-and-cocoa/</link>
		<comments>http://blog.jayway.com/2009/05/06/regular-expressions-and-cocoa/#comments</comments>
		<pubDate>Wed, 06 May 2009 19:36:27 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[regex]]></category>

		<guid isPermaLink="false">http://79.125.9.149/?p=1617</guid>
		<description><![CDATA[Regular expressions is a powerful tool for solving many problems related to text. It can be misused as any good tool, but there are moments when they are the best solution for a given problem. At those moments the lack of regular expressions for Cocoa on Mac OS X and Cocoa Touch on iPhone OS [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Regular_expression">Regular expressions</a> is a powerful tool for solving many problems related to text. It can be misused as any good tool, but there are moments when they are the best solution for a given problem. At those moments the lack of regular expressions for Cocoa on Mac OS X and Cocoa Touch on iPhone OS is a pain in the butt.</p>
<p>Or are regular expressions really missing? Regular expressions can be used with <code>NSPredicate</code> that is part of Core Data, available since Mac OS X 10.4 and officially announced for iPhone OS 3.0. Cocoa's <code>WebView</code> and the equivalent <code>UIWebView</code> in Cocoa Touch both support JavaScript with regular expressions. So there sure is regular expressions available on the platforms, but how do you make it available for your own code?</p>
<h3>An Ugly Solution</h3>
<p>You can actually get access to the regular expression engine through JavaScript, unfortunately this requires a roundtrip through <a href="http://webkit.org/">WebKit</a>. On an iPhone this means you have to use an off-screen instance of <code>UIWebView</code>, and delegate execution of regular expression to it. </p>
<p>The complexity of an off-screen <code>WebView</code> or <code>UIWebView</code> could be hidden by a utility class. But the extra glue code needed to make something useful out of the single method <code>stringByEvaluatingJavaScripFromString:</code>, would be allot.</p>
<h3>What Apple Recommends</h3>
<p>For most problems the official stance is correct; do not use regular expressions. Instead use <code>NSScanner</code>, that is perfect for sequentially parse texts. It is very fast and can substitute any regular expressions that only relies on:
<ul>
<li>Character sets</li>
<li>Exact string matches</li>
<li>Numerical matches</li>
<li>Uniform input text</li>
</ul>
<p>These conditions hold true to 95% of everything regular expressions is ever used for. For the other 5%, Apple leaves you to fend for your own.</p>
<h3>Other Solutions</h3>
<p><a href="http://www.pcre.org/">PCRE</a> compiles perfectly with Cocoa, since it is written in C, one of the many advantages of Objective-C. PCRE is very capable, and almost a standard, but also very large. For an iPhone application the PCRE implementation could end up as the majority of your executables file-size. If this is something you can live with, then the open source <a href="http://regexkit.sourceforge.net/">RegexKit</a> framework wraps PCRE in Cocoa and Cocoa Touch friendly Objective-C.</p>
<p>Another regular expressions framework is <a href="http://www8.ocn.ne.jp/~sonoisa/OgreKit/">OgreKit</a>. The advantage of OgreKit is full unicode support, with the same disadvantage of size. And the fact that the documentation is in Japanese.</p>
<h3>A Pretty Solution</h3>
<p>It turns out that Mac OS X for years, and iPhone OS since inception, has been shipped with a perfectly good regular expressions engine. This engine is based on the <a href="http://site.icu-project.org/">ICU specification</a>, so it works perfectly with unicode and is well on par with PCRE for functionality. This framework is simply called ICU Core, and has a C interface. But for a Cocoa programmers the C interface is not nice enough, and thankfully <a href="http://twitter.com/johnengelhart">John Engelhart</a> has done this work for us, with <a href="http://regexkit.sourceforge.net/RegexKitLite/">RegexKitLite</a>. RegexKitLite is a little brother to RegexKit that wrapps ICU Core instead of PCRE.</p>
<p>RegexKitLite is published under <a href="http://en.wikipedia.org/wiki/BSD_license">BSD license</a>, and is simply two files you add to your project, fully compatible with all available versions of both Mac OS X and iPhone OS. The tricky part is that ICU Core is not a public API officially supported by Apple, even though it has existed unchanged for years. Good news is that using ICU Core is not a show stopper for publishing on the iPhone App Store, application out there already uses it, both <a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=284540316&mt=8">well known</a> and <a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=305963116&mt=8">not so well known</a>.</p>
<h3>Setting Up RegexKitLite</h3>
<ol>
<li>Download the latest version from the <a href="http://sourceforge.net/project/showfiles.php?group_id=204582&package_id=268643">sourceforge webpage</a>, or <a href="http://sourceforge.net/scm/?type=svn&group_id=204582">SVN</a>.</li>
<li>Add <code>RegexKitLite.h</code> and <code>RegexKitLite.m</code> to your project.</li>
<li>Link your project against ICU Core, by adding the linker flag <code>-licucore</code> to <em>Other Linker Flags</em> under your projects build settings.</li>
</ol>
<p>Optionally you can also add the documentation to Xcode with these easy steps:</p>
<ol>
<li>Open <em>Help -> Documtantion</em>.</li>
<li>Press the Gears button in the lower left corder, and select <em>New Subscription...</em>.</li>
<li>Enter <code>feed://regexkit.sourceforge.net/RegexKitLiteDocSets.atom</code> as URL.</li>
</ol>
<h3>Using RegexKitLite</h3>
<p>This post is not a tutorial on regular expressions, but a tutorial on a partical API for executing regular expressions. If you want to learn more about regular expressions themselves I would recomend you look at <a href="http://www.regular-expressions.info">Regular Expressions.info</a>.</p>
<p>RegexKitLite provides it's functionality as categories on <code>NSString</code> and <code>NSMutableString</code>. This way using regular expressions with Cocoa is just as easy and normal string manipulation. This is best described using examples.</p>
<p>A simple example that normalizes a text with single white spaces, kind of like how a HML renderer would do, so this is handy when scraping web pages:</p>
<pre class="objc"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* source = @<span style="color: #666666;">&quot;One<span style="color: #666666; font-weight: bold;">\t</span> Two <span style="color: #666666; font-weight: bold;">\n</span>Three &quot;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* result = <span style="color: #002200;">&#91;</span>source stringByReplacingOccurancesOfRegex:@<span style="color: #666666;">&quot;<span style="color: #666666; font-weight: bold;">\\</span>s+&quot;</span>
    withString:@<span style="color: #666666;">&quot; &quot;</span><span style="color: #002200;">&#93;</span>;
NSLog<span style="color: #002200;">&#40;</span>source<span style="color: #002200;">&#41;</span>;
NSLog<span style="color: #002200;">&#40;</span>result<span style="color: #002200;">&#41;</span>;</pre>
<p>Or you can split a text, such as semi-colon delimeted data:</p>
<pre class="objc"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* source = @<span style="color: #666666;">&quot;Test;12;Y&quot;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>* columns = <span style="color: #002200;">&#91;</span>source componentsSeparatedByRegex:@<span style="color: #666666;">&quot;;<span style="color: #666666; font-weight: bold;">\\</span>s*&quot;</span><span style="color: #002200;">&#93;</span>;
NSLog<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>columns description<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;</pre>
<p>And you can extract more complex data using capture groups:</p>
<pre class="objc"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* source = @<span style="color: #666666;">&quot;&lt;foo no=<span style="color: #666666; font-weight: bold;">\&quot;</span>12<span style="color: #666666; font-weight: bold;">\&quot;</span>&gt;Name&lt;/foo&gt;&quot;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* regex = @<span style="color: #666666;">&quot;&lt;foo no=<span style="color: #666666; font-weight: bold;">\&quot;</span>(.+?)<span style="color: #666666; font-weight: bold;">\&quot;</span>&gt;(.*?)&lt;/foo&gt;&quot;</span>;
<span style="color: #0000ff;">int</span> no = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>source stringByMatching:regex capture:<span style="color: #0000dd;">1</span><span style="color: #002200;">&#93;</span> intValue<span style="color: #002200;">&#93;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* data = <span style="color: #002200;">&#91;</span>source stringByMatching:regex capture:<span style="color: #0000dd;">2</span><span style="color: #002200;">&#93;</span>;
NSLog<span style="color: #002200;">&#40;</span>@<span style="color: #666666;">&quot;no: %d data: %@&quot;</span>, no, data<span style="color: #002200;">&#41;</span>;</pre>
<p>This may look like it could be slow to perform matches on the same regular expression twice, but it is not. RegexKitLite is very smart, and will cache your previous matches for very high performance.</p>
<p>RegexKitLite is a very capable, and also much active open source project, with version 3.0 as a release candidate in SVN. Use it, and use it well.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/06/regular-expressions-and-cocoa/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Adding Sorted Inserts to Cocoa Arrays</title>
		<link>http://blog.jayway.com/2009/03/28/adding-sorted-inserts-to-uimutablearray/</link>
		<comments>http://blog.jayway.com/2009/03/28/adding-sorted-inserts-to-uimutablearray/#comments</comments>
		<pubDate>Sat, 28 Mar 2009 22:39:22 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1441</guid>
		<description><![CDATA[NSArray and NSMutableArray have methods for sorting arrays, NSArray returns new sorted arrays and NSMutableArray can be sorted in place. The sort methods comes in three flavours; using a function, using a selector, or using an array of NSSortDescriptor objects. NSArray admits to sorts being a slow operation, and adds a method pair for comultive [...]]]></description>
			<content:encoded><![CDATA[<p><code>NSArray</code> and <code>NSMutableArray</code> have methods for sorting arrays, <code>NSArray</code> returns new sorted arrays and <code>NSMutableArray</code> can be sorted in place. The sort methods comes in three flavours; using a function, using a selector, or using an array of <code>NSSortDescriptor</code> objects.</p>
<p><code>NSArray</code> admits to sorts being a slow operation, and adds a method pair for comultive sorts using hints. This way the operation is done in <em>O(P*LOG(P)+N)</em> time, instead of <em>O(N*LOG(N))</em>. Where <em>N</em> is number of elements, and <em>P</em> is number of additions and deletions since the last sort. Unfortunately that do not work on <code>NSMutableArray</code>. So even if memory consumption will not hit the roof, release retain cycles will take it's toll.</p>
<p>So why not add methods to find the insertion points, and insert new objects into already sorted <code>NSArray</code> and <code>NSMutableArray</code> object? Best case for inserting single elements should be <em>O(LOG(N)^2)</em>, so lets hit that target. And on the way there, we will learn how to;
<ul>
<li>Add functionality to standard classes using categories.</li>
<li>Implement high performant Obj-C code for tight loops.</li>
</ul>
<h3>New Categories on <code>NSArray</code> and <code>NSMutableArray</code></h3>
<p>This will become a bit complex on the inside, but the public front should be as simple as this:</p>
<pre class="objc"><span style="color: #339900;">#import &lt;Foundation/Foundation.h&gt;</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a> <span style="color: #002200;">&#40;</span>CWSortedInsert<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingfunction:<span style="color: #002200;">&#40;</span>NSInteger <span style="color: #002200;">&#40;</span>*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">void</span> *<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>compare
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingDescriptors:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>descriptors;
&nbsp;
<span style="color: #0000ff;">@end</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMutableArray.html"><span style="color: #0000ff;">NSMutableArray</span></a> <span style="color: #002200;">&#40;</span>CWSortedInsert<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>insertObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingfunction:<span style="color: #002200;">&#40;</span>NSInteger <span style="color: #002200;">&#40;</span>*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">void</span> *<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>compare
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>insertObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject sortedUsingSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>insertObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject sortedUsingDescriptors:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>descriptors;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3>Base Implementation</h3>
<p>We want to follow suit with <code>NSArray</code> and <code>NSMutableArray</code>, so we too shall support inserts based on functions, selectors, and an array of sort descriptors. In practice we only need to implement <code>indexForInsertingObject:sortedUsingfunction:context:</code>, the other methods can use this one, each with a private compare method of their own. So we begin by implementing this method.</p>
<pre class="objc"><span style="color: #339900;">#import &quot;NSArray+CWSortedInsert.h&quot;</span>
<span style="color: #339900;">#import &lt;objc/runtime.h&gt;</span>
&nbsp;
<span style="color: #0000ff;">@implementation</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a> <span style="color: #002200;">&#40;</span>CWSortedInsert<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingfunction:<span style="color: #002200;">&#40;</span>NSInteger <span style="color: #002200;">&#40;</span>*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">void</span> *<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>compare
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context;
<span style="color: #002200;">&#123;</span>
  NSUInteger index = <span style="color: #0000dd;">0</span>;
  NSUInteger topIndex = <span style="color: #002200;">&#91;</span>self count<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">IMP</span> objectAtIndexImp = <span style="color: #002200;">&#91;</span>self methodForSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>objectAtIndex:<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">while</span> <span style="color: #002200;">&#40;</span>index &lt; topIndex<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    NSUInteger midIndex = <span style="color: #002200;">&#40;</span>index + topIndex<span style="color: #002200;">&#41;</span> / <span style="color: #0000dd;">2</span>;
    <span style="color: #0000ff;">id</span> testObject = objectAtIndexImp<span style="color: #002200;">&#40;</span>self, <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>objectAtIndex:<span style="color: #002200;">&#41;</span>, midIndex<span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>compare<span style="color: #002200;">&#40;</span>anObject, testObject, context<span style="color: #002200;">&#41;</span> &lt; <span style="color: #0000dd;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      index = midIndex + <span style="color: #0000dd;">1</span>;
    <span style="color: #002200;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #002200;">&#123;</span>
      topIndex = midIndex;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> index;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #ff0000;">// More code here...</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>The Objective-C runtime header <code><objc/runtime.h></code> is included so we can go around the usual method dispatch, and instead use the method implementations as function pointers. In most cases this is a neglectable optimization, for this case we will be the bottle neck since we are intended to be the low level API.</p>
<p>The algorithm is a simple binary search, and we have a worst case <em>O(LOG(N)^2)</em> time for index search. Using this for implementing the sibling method in <code>NSMutableArray</code> is as simple as this:</p>
<pre class="objc"><span style="color: #0000ff;">@implementation</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMutableArray.html"><span style="color: #0000ff;">NSMutableArray</span></a> <span style="color: #002200;">&#40;</span>CWSortedInsert<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>insertObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingfunction:<span style="color: #002200;">&#40;</span>NSInteger <span style="color: #002200;">&#40;</span>*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">void</span> *<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>compare
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context;
<span style="color: #002200;">&#123;</span>
  NSUInteger index = <span style="color: #002200;">&#91;</span>self indexForInsertingObject:anObject
      sortedUsingfunction:compare context:context<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self insertObject:anObject atIndex:index<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #ff0000;">// More code here...</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3>Sort Using Selector</h3>
<p>With functions in place, writing a utility compare function that uses selectors, and can be used with our <code>indexForInsertingObject:sortedUsingfunction:context:</code> method is a breeze.</p>
<pre class="objc"><span style="color: #0000ff;">static</span> NSComparisonResult cw_SelectorCompare<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span> a, <span style="color: #0000ff;">id</span> b, <span style="color: #0000ff;">void</span>* aSelector<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#40;</span>NSComparisonResult<span style="color: #002200;">&#41;</span>objc_msgSend<span style="color: #002200;">&#40;</span>a, <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector, b<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self indexForInsertingObject:anObject
      sortedUsingfunction:&amp;cw_SelectorCompare context:aSelector<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>Notice that <code>objc_msgSend(id, SEL, ...)</code> is used instead of the <code>performSelector:withObject:</code> method. This is a small performance improvement, as what <code>performSelector:withObject:</code> do behind the scene is just a call to <code>objc_msgSend()</code> anyway. We have removed one method invokation per compare.</p>
<h3>Sort Using Sort Descriptors</h3>
<p>Or rather sort with an array or <code>NSSortDescriptor</code> objects. This will be the least performant, but also the most flexible sort. An array of sort descriptors is used because we want to be able to sort using several criteria, one sort descriptor per criteria. For example when sorting on last name, then first name, or even more complex sorts.</p>
<p>A <code>NSSortDescriptor</code> is initialized with a key, sort order (ascending or descending) and optionally a selector to do the comparison with, by default <code>compare:</code>. There are quite a few method invokations involved, and it will be good for performance to avoid as many as we can.</p>
<p>Just as <code>performSelector:withObject:</code> uses <code>objc_msgSend()</code> behind the scene, so do <code>objc_msgSend</code> use a function pointer internally. After doing a hash-table lookup with the selector as key that is. This look-up is cached and very fast, but avoiding it all together is always faster. So let us fetch those when the category is first loaded, and do our calls straight through the functions pointers avoiding at least two or more function calls for each compare operation.</p>
<pre class="objc"><span style="color: #0000ff;">static</span> <span style="color: #0000ff;">IMP</span> cw_compareObjectToObjectImp = <span style="color: #0000ff;">NULL</span>;
<span style="color: #0000ff;">static</span> <span style="color: #0000ff;">IMP</span> cw_ascendingImp = <span style="color: #0000ff;">NULL</span>;
&nbsp;
+<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>initialize;
<span style="color: #002200;">&#123;</span>
  cw_compareObjectToObjectImp = <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSSortDescriptor.html"><span style="color: #0000ff;">NSSortDescriptor</span></a>
      instanceMethodForSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>compareObject:toObject:<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
  cw_ascendingImp = <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSSortDescriptor.html"><span style="color: #0000ff;">NSSortDescriptor</span></a>
      instanceMethodForSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>ascending<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>The class method <code>inilialize</code> is kind of magic, it is called once for each class and category, when the class or category is loaded into the run-time. It is the Obj-C equivalent of static initializers.</p>
<p>With the function pointers to the hot-spot method implementations in hand, here is the fast implementation:</p>
<pre class="objc"><span style="color: #0000ff;">static</span> NSComparisonResult cw_DescriptorCompare<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span> a, <span style="color: #0000ff;">id</span> b, <span style="color: #0000ff;">void</span>* descriptors<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
  NSComparisonResult result = NSOrderedSame;
  <span style="color: #0000ff;">for</span> <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSSortDescriptor.html"><span style="color: #0000ff;">NSSortDescriptor</span></a>* sortDescriptor in <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>descriptors<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    result = <span style="color: #002200;">&#40;</span>NSComparisonResult<span style="color: #002200;">&#41;</span>cw_compareObjectToObjectImp<span style="color: #002200;">&#40;</span>sortDescriptor,
        <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>compareObject:toObject:<span style="color: #002200;">&#41;</span>, a, b<span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>result != NSOrderedSame<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>!cw_ascendingImp<span style="color: #002200;">&#40;</span>sortDescriptor, <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>ascending<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      	result = <span style="color: #0000dd;">0</span> - result;
      <span style="color: #002200;">&#125;</span>
      <span style="color: #0000ff;">break</span>;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> result;
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingDescriptors:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>descriptors;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self indexForInsertingObject:anObject
      sortedUsingfunction:&amp;cw_DescriptorCompare context:descriptors<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<h3>Conclusions</h3>
<p>The fact that Objective-C is a strict superset of C have some good benefits. The obvious one is that your Obj-C code is both source-code and binary compatible with the vast collection of code that has been written in C over the past 30+ years.</p>
<p>The second benefit is that when performance is needed, Obj-C gives us as developers full access to the internals of the dynamic run-time.</p>
<p>But best of all, most developers never need to care. They can, blissfully unaware, reap the benefits of the performance tuning under the hood. Tuning by both Apple and considerate third party library developers willing to go the extra mile (or a few metres at least).</p>
<p>The code is released under BSD license, and works on both Mac OS X and iPhone OS. You can <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/nsarraycwsortedinsert.zip'>download it here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/28/adding-sorted-inserts-to-uimutablearray/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Bridging the Gap Between Java and Cocoa</title>
		<link>http://blog.jayway.com/2009/03/24/bridging-the-gap-between-java-and-cocoa/</link>
		<comments>http://blog.jayway.com/2009/03/24/bridging-the-gap-between-java-and-cocoa/#comments</comments>
		<pubDate>Tue, 24 Mar 2009 09:21:46 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1230</guid>
		<description><![CDATA[Many Java developers are looking at new dynamic languages, such as Groovy and JRuby, mostly because of the freedom and rapid development that a dynamic language allows. Some of my colleagues are also looking at Cocoa and feel daunted at the sight of Objective-C. Here I will use a small example that is easy and [...]]]></description>
			<content:encoded><![CDATA[<p>Many <a href="http://www.sun.com/java/">Java</a> developers are looking at new dynamic languages, such as <a href="http://groovy.codehaus.org/">Groovy</a> and <a href="http://jruby.codehaus.org/">JRuby</a>, mostly because of the freedom and rapid development that a dynamic language allows. Some of my colleagues are also looking at <a href="http://developer.apple.com/cocoa/">Cocoa</a> and feel daunted at the sight of <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/">Objective-C</a>. </p>
<p>Here I will use a small example that is easy and natural for <a href="http://www.ruby-lang.org/">Ruby</a>, but equally hard for Java and Obj-C. That way both languages stand on equal grounds for comparison.</p>
<p>This article explains the Objective-C parts in detail, and Java in brief. It is assumed that you as a reader understands Java well. Many concept in Java and Obj-C are identical, but with different names. I will be using the Java names in Java context, and the Obj-C names in Obj-C context. Therefore; memorize this short glossary:</p>
<pre>Java      -> Obj-C
interface -> protocol
this      -> self
null      -> nil</pre>
<p>Cocoa relies heavily on features in the Obj-C langauges, so even if Cocoa apps can be written, and is so <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/RubyPythonCocoa/Introduction/Introduction.html">supported by Apple</a>, in Ruby or Python; Obj-C is the only language that can tap into the full power of Cocoa.</p>
<p>Cocoa on Mac OS X is an umbrella framework for Foundation and AppKit. Cocoa Touch on iPhone OS is an umbrella framework for Foundation and UIKit. This post only uses features from the shared Foundation framework, and this is applicable for both Mac OS X and iPhone OS. </p>
<h3>The Ruby Problem</h3>
<p>Ruby makes it extremely easy to work with arrays. For the sake of this post I want to convert an array of numbers into an array of strings. Performing the same operation on an arbitrary list of objects, and then resturn a list with the results.</p>
<pre class="ruby">list = <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">12</span>, <span style="color:#006666;">42</span>, <span style="color:#006666;">366</span><span style="color:#006600; font-weight:bold;">&#93;</span>
results = list.<span style="color:#9900CC;">collect</span> <span style="color:#006600; font-weight:bold;">&#123;</span> |item| item.<span style="color:#9900CC;">to_s</span> <span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> results</pre>
<p>First line sets up an array of numbers, and the second line creates a new array by executing a block against each element, and then we print it out. The block can be seen as a closure, Java nor Obj-C have closures, at least not yet. Objective-C 2.1 will be public this summer and introduce blocks, that can be seen as closures.</p>
<p>With no closures at hand today, both Java and Obj-C will have to solve the problem by executing a method on each element. In this example <code>toString()</code> in Java and the Cocoa equivalent <code>description</code>.</p>
<h3>Java Implementation</h3>
<p>For the Java implementation we need to introduce a utility class. This utility class I call <code>ListCollector</code>, and it uses generics to allow for different kinds of inputs and results. This utility class could be implemented like this:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ListCollector <span style="color: #66cc66;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Collector&lt;R, E&gt; <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">public</span> R collect<span style="color: #66cc66;">&#40;</span>E element<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> &lt;R, E&gt; List&lt;R&gt; collect<span style="color: #66cc66;">&#40;</span>List&lt;E&gt; list, Collector&lt;R, E&gt; collector<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        List&lt;R&gt; results = <span style="color: #000000; font-weight: bold;">new</span> ArrayList&lt;R&gt;<span style="color: #66cc66;">&#40;</span>list.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>E item : list<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            R result = collector.<span style="color: #006600;">collect</span><span style="color: #66cc66;">&#40;</span>item<span style="color: #66cc66;">&#41;</span>;
            results.<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span>result<span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> results;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span></pre>
<p>Our utility function collect takes two arguments; a <code>List</code> with elements, and a Collector implementation to invoke on each element. This do not use a closure as in the Ruby example.</p>
<p>A simple example of how to use this utility in the same veine as in the previous Ruby example:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Example <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #993333;">void</span> main<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> args<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        List&lt;Number&gt; list = <span style="color: #000000; font-weight: bold;">new</span> ArrayList&lt;Number&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        list.<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">12</span><span style="color: #66cc66;">&#41;</span>;
        list.<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">42</span><span style="color: #66cc66;">&#41;</span>;
        list.<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">366</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        List&lt;String&gt; results = ListCollector.<span style="color: #006600;">collect</span><span style="color: #66cc66;">&#40;</span>list,
                <span style="color: #000000; font-weight: bold;">new</span> ListCollector.<span style="color: #006600;">Collector</span>&lt;String, Number&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                    <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> collect<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ANumber+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Number</span></a> element<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
                        <span style="color: #000000; font-weight: bold;">return</span> element.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
                    <span style="color: #66cc66;">&#125;</span>
                <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>results<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<h3>Cocoa Interaface</h3>
<p>In Cocoa you never have utility classes, instead you use categories to add new functions to already existing classes. A category can be seen as a mix-ins, it allows us to add and replace class and instance methods, as well as protocol conformance on already existing classes.</p>
<p>That is the good stuff, the bad stuff is that Obj-C do not know of final. So if an implementation is brittle, the only safety against bad programmers is the documentation you write. In fact Obj-C do not know of visibility, all methods are public. You can only hide a method by not displaying it in the public interface of your classes (your users may still guess at the names and use it anyway).</p>
<p>That leads us to interfaces, Obj-C just as C and C++ uses interface files; <code>.h</code> files. So lets define our category:</p>
<pre class="objc"><span style="color: #339900;">#import &lt;Foundation/Foundation.h&gt;</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a> <span style="color: #002200;">&#40;</span>CWCollect<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>resultsFromMakingObjectsPerformSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
        withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>First thing we note here is that the method name is quite long; <code>resultsFromMakingObjectsPerformSelector:withObject:</code>, and that arguments are interleaved. At first glance it might look like named arguments, this is an illusion, they are merely interleaved with the <code>:</code> character. Looks strange, but the result is surprisingly readable and self describing code.</p>
<p>Note that is do not use a closure as in Ruby, nor an inner class as in Java, but a reference to a method identifier in the form of the <code>SEL</code> argument.</p>
<h3>Cocoa Implementation</h3>
<p>Just as C and C++ has interface files, so do Obj-C have implementation files; <code>.m</code> files, or <code>.mm</code> for Objective-C++ where you can mix C++ with Objective-C.</p>
<p>The implementation is quite familiar:</p>
<pre class="objc"><span style="color: #339900;">#import &quot;NSArray+CWCollect.h&quot;</span>
&nbsp;
<span style="color: #0000ff;">@implementation</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a> <span style="color: #002200;">&#40;</span>CWCollect<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>resultsFromMakingObjectsPerformSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
        withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject;
<span style="color: #002200;">&#123;</span>
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMutableArray.html"><span style="color: #0000ff;">NSMutableArray</span></a>* results = <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMutableArray.html"><span style="color: #0000ff;">NSMutableArray</span></a> arrayWithCapacity:<span style="color: #002200;">&#91;</span>self count<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #0000ff;">for</span> <span style="color: #002200;">&#40;</span>id&lt;NSObject&gt; item in self<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #0000ff;">id</span> result = <span style="color: #002200;">&#91;</span>item performSelector:aSelector withObject:anObject<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span>results addObject:<span style="color: #002200;">&#40;</span>result != <span style="color: #0000ff;">nil</span><span style="color: #002200;">&#41;</span> ? result : <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSNull.html"><span style="color: #0000ff;">NSNull</span></a> <span style="color: #0000ff;">null</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>results copy<span style="color: #002200;">&#93;</span> autorelease<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>First we create a <code>NSMutableArray</code>, in Cocoa there are two classes for arrays; <code>NSArray</code> that is immutable, and the subclass <code>NSMutableArray</code> that is mutable. Then we use the for each statement to iterate over our input array. Then comes the first real difference from Java, and a clear display of the dynamic nature. Obj-C, nor Cocoa have support for generics. The use of the generic <code>id</code> object type avoids the need for most typecast, but you should be aware that they implicitly are there.</p>
<p>Methods are first class citizens in Obj-C, not tucked away in a utility package. A method in Obj-C consists of two parts; the selector and the implementation. The selector has the type <code>SEL</code>, and the implementation is <code>IMP</code>. Both can be passed around just as any other primitive type or object instance. </p>
<p>The selector is the identification of the method, think of it as the name. The selector is shared for all classes implementing a method with the same signature. If one class implements <code>someMethod:</code> and another class, in a completely other even dynamically loaded framework, also implements <code>someMethod:</code> both are guaranteed to be equal. The root object <code>NSObject</code> in Cocoa implements methods for dynamically invocing methods baseds on selectors, one of them is the one used in the code above <code>performSelector:withObject:</code>.</p>
<p>The implementation of a method is a function pointer to the actual executable code that implements the method. It can be shared between classes, as is often the case for subclasses. But can also be freely passes around, and exchanged for some quite powerful and useful tricks.</p>
<h3>Cocoa Use-case Example</h3>
<p>Obj-C is a strict superset of C, so just as you have a main function in C, so do Obj-C. For most Cocoa application you never need to worry about this, the template from Xcode will generate the main function and all you see is OOP goodnes. For this small example I will do the test code in a main function of my own. If you cut and paste code from this example, be sure to create a project from the "Command Line Utility"->"Foundation Tool" template in Xcode.</p>
<pre class="objc"><span style="color: #339900;">#import &lt;Foundation/Foundation.h&gt;</span>
<span style="color: #339900;">#import &quot;NSArray+CWCollect.h&quot;</span>
&nbsp;
<span style="color: #0000ff;">int</span> main <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">int</span> argc, <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</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>
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSAutoreleasePool.html"><span style="color: #0000ff;">NSAutoreleasePool</span></a> * pool = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSAutoreleasePool.html"><span style="color: #0000ff;">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/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>* list = <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a> arrayWithObjects:<span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSNumber.html"><span style="color: #0000ff;">NSNumber</span></a> numberWithInt:<span style="color: #0000dd;">12</span><span style="color: #002200;">&#93;</span>,
            <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSNumber.html"><span style="color: #0000ff;">NSNumber</span></a> numberWithInt:<span style="color: #0000dd;">42</span><span style="color: #002200;">&#93;</span>, <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSNumber.html"><span style="color: #0000ff;">NSNumber</span></a> numberWithInt:<span style="color: #0000dd;">336</span><span style="color: #002200;">&#93;</span>, <span style="color: #0000ff;">nil</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>* result = <span style="color: #002200;">&#91;</span>list
            resultsFromMakingObjectsPerformSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>description<span style="color: #002200;">&#41;</span>
            withObject:<span style="color: #0000ff;">nil</span><span style="color: #002200;">&#93;</span>;
&nbsp;
    NSLog<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>result description<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
    <span style="color: #002200;">&#91;</span>pool drain<span style="color: #002200;">&#93;</span>;
    <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>The <code>NSAutoreleasePool</code> is part of Cocoa, and is used to seemingly garbage collected framework. Cocoa for Mac OS X can be garbage collected, Cocoa Touch for iPhone OS is not garbage collected.</p>
<p>The second statement created an array instance with three <code>NSNumber</code> objects. <code>NSNumber</code> is equivalent to <code>java.lang.Number</code> and all of it's subclasses, Cocoa do not have a separate subclass of <code>NSNumber</code> for each primitive type. <code>NSNumber</code> is a subclass of <code>NSValue</code>, that can hold any C type value including structs and unions.</p>
<p>The third statement is where we call the method we defined and implemented above. Note how we call this on a stock Cocoa class, not on a utility class. We use the <code>@selector()</code> compiler directive to retrieve a selector of <code>SEL</code> type from a human readable name, and pass <code>nil</code> the Objective-C equivalent of null as argument.</p>
<p>Lastly we send the result converted to a string to NSLog() function. NSLog() is a C macro with printf syntax that is used to send text to standard out. NSLog() can be removed from release builds.</p>
<h3>Last Words</h3>
<p>It is important to understand the concept of selectors, and how passing around <code>SEL</code> arguments works. In Java libraries callbacks are often handles using listener interfaces, where the listener implements an interface and a specific method is called. In Cocoa listeners are implemented using the target-action paradigm, where the intended listener is passed along with the <code>SEL</code> specifying which method to send the callback to.</p>
<p>As an example when setting up the event listener for user tapping a control in Cocoa Touch on iPhone OS:</p>
<pre class="objc"><span style="color: #002200;">&#91;</span>myButton addTarget:self action:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>buttonTapped:<span style="color: #002200;">&#41;</span>
        forControlEvents:UIControlEventTouchUpInside<span style="color: #002200;">&#93;</span>;</pre>
<p>What this means is that the need for anonymous inner classes is removed, and the same class can in a natural way receive the same event from different senders. </p>
<p>For more complex, or grouped event handling protocols are used. The classes conforming to the listeners protocols are not referred to as listener, but as delegates, yet again different name but same concept. But even now the dynamic language come into play, as a class is not required to implement all methods from a protocol in order to conform to it (Think of it as if some methods in a Java interface could be optional, and then are treaded as no-ops).</p>
<p>A protocol in Obj-C can have optional methods. Implementor of the <code>NSTableViewDataSource</code> protocol may for example choose to implement, or not to implement the method <code>tableView:setObjectValue:forTableColumn:row:</code>. If not implemented the table is read-only, by implementing this single method the table is editable and functionality such as pasting into the cells is provided for free.</p>
<p>It is very important for developers new to Cocoa and Obj-C to grasp the concepts of <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html#//apple_ref/doc/uid/TP40002974-CH7-SW14">target-action</a>, and <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html#//apple_ref/doc/uid/TP40002974-CH7-SW18">delegates</a>. This is the core principles that drive the application frameworks for Mac OS X and iPhone OS.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/24/bridging-the-gap-between-java-and-cocoa/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>UIToolbars in iPhone OS 2.x</title>
		<link>http://blog.jayway.com/2009/03/22/uitoolbars-in-iphone-os-2x/</link>
		<comments>http://blog.jayway.com/2009/03/22/uitoolbars-in-iphone-os-2x/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 16:39:42 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1293</guid>
		<description><![CDATA[The new release of iPhone OS 3.0 adds some nice API:s for managing a contextual toolbar. This is well needed as toolbars in the current iteration of iPhone OS is not only poorly documented, it is also quite hard to do right. So I will go over how to do toolbars the right way, for [...]]]></description>
			<content:encoded><![CDATA[<p>The new release of iPhone OS 3.0 adds some nice API:s for managing a contextual toolbar. This is well needed as toolbars in the current iteration of iPhone OS is not only poorly documented, it is also quite hard to do right. So I will go over how to do toolbars the right way, for all who want to implement them the old way before this summer, and for all who think they need to support older versions after then (Read my <a href="http://blog.jayway.com/2009/03/18/iphone-os-and-the-lowest-common-denominator/">previous post</a> on why backward compatibility is not an issue for iPhone OS developers).</p>
<h3>The Problem</h3>
<p>The most intuitive way to create and use a <code>UIToolbar</code> is to add it manually for each of your view controllers. If your application is very simple this could be the right thing to do, but if our application uses a <code>UINavigationController</code> then it is the wrong way to do it.</p>
<p>If you look at the Mail application you will notice how the toolbar stays in place, and the items on the toolbar cross fades when you navigate the application hierarchy. You might also have noticed that the toolbar do not cross fade, but rather is pushed, if you add a toolbar to each of the view trees of your own view controllers. This is because your toolbar is then part of the wrong three hierarchy, as shown in this image.<br />
<div id="attachment_1294" class="wp-caption alignright" style="width: 490px"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/layout_wrong.png" alt="Screen estate as owned by different view controllers." title="layout_wrong" width="320" height="312" class="size-full wp-image-1294" /><p class="wp-caption-text">Screen estate as owned by different view controllers.</p></div></p>
<p>You will find a few solutions if you Goole on the topic, all of them that I have found are dead wrong. They tend to use <code>self.view.superview</code> on the view controller instance to slide the toolbar up one level in the hierarchy. It works, most of the time, but is an ugly hack that is not future proof.</p>
<h3>A Better Solution</h3>
<p>The reason the toolbar is pushed off screen is that the toolbar is owned by the navigation controller,as we saw in the image above, and a navigation controller pushes it's content. The view hierarchy we would like to have is instead something like this.<br />
<div id="attachment_1300" class="wp-caption alignright" style="width: 530px"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/layout_correct.png" alt="Screen estate as owned by different view controllers." title="layout_correct" width="341" height="320" class="size-full wp-image-1300" /><p class="wp-caption-text">Screen estate as owned by different view controllers.</p></div></p>
<p>In this setup the navigation controller can push the content, as it is intended to do, and the custom toolbar controller can manage a static <code>UIToolbar</code> with cross fades. Only problem is; this custom toolbar controller do not exist, and we must implement it on our own. Luckily not many lines of code is needed.</p>
<h3>Custom Toolbar Conroller Requirement</h3>
<p>The custom toolbar controller should be a subclass of <code>UIViewController</code>, that way it's fits nicely into the Cocoa Touch framework, and can nicely be fitted into any well written application.</p>
<p>The custom toolbar controller should manage a view consisting of a <code>UIToolbar</code> instance, and a view that is fetched from another view controller. This is modelled after how a <code>UINavigationController</code> manages a view that consists of a <code>UINavigationBar</code> and the view fetched from other view controllers. This way any well written view controller can be used with our custom toolbar controller.</p>
<p>Lastly our custom toolbar controller should implement the <code>UINavigationControllerDelegate</code> protocol, so that we can listen to events as view controllers are pushed and poped from the navigation stack, and update the toolbar with contextual toolbar items. Just as the navigation controller updates it's title by fetching the title property of the managed view controllers, so will our custom toolbar controller update the toolbar items by fetching the toolbarItems property if available.</p>
<h3>Toolbar Controller Interface</h3>
<p>The interface will be sparse, all we need is an initializer for creating a toolbar controller with another view controller providing the main content, and for sports two properties to access the content view controller, and the toolbar itself.</p>
<pre class="objc"><span style="color: #339900;">#import &lt;UIKit/UIKit.h&gt;</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> CWToolbarController : UIViewController &lt;UINavigationControllerDelegate&gt; <span style="color: #002200;">&#123;</span>
<span style="color: #0000ff;">@private</span>
    UIViewController* _contentViewController;
    UIToolbar* _toolbar;
<span style="color: #002200;">&#125;</span>
&nbsp;
@property<span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> UIViewController* contentViewController;
@property<span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> UIToolbar* toolbar;
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>initWithContentViewController:<span style="color: #002200;">&#40;</span>UIViewController*<span style="color: #002200;">&#41;</span>contentViewController;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3>Toolbar Controller Implementation</h3>
<p>The grunt work for implementing the toolbar controller do not need any further explanation.</p>
<pre class="objc"><span style="color: #339900;">#import &quot;CWToolbarController.h&quot;</span>
&nbsp;
<span style="color: #0000ff;">@implementation</span> CWToolbarController
&nbsp;
@synthesize contentViewController = _contentViewController;
@synthesize toolbar = _toolbar;
&nbsp;
- <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>initWithContentViewController:<span style="color: #002200;">&#40;</span>UIViewController*<span style="color: #002200;">&#41;</span>contentViewController;
<span style="color: #002200;">&#123;</span>
    self = <span style="color: #002200;">&#91;</span>super init<span style="color: #002200;">&#93;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>self<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        _contentViewController = <span style="color: #002200;">&#91;</span>contentViewController retain<span style="color: #002200;">&#93;</span>;
        <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>_contentViewController isKindOfClass:<span style="color: #002200;">&#91;</span>UINavigationController <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>UINavigationController*<span style="color: #002200;">&#41;</span>_contentViewController<span style="color: #002200;">&#41;</span>.delegate = self;
        <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#125;</span>
	<span style="color: #0000ff;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #ff0000;">// More code here...</span>
&nbsp;
- <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>dealloc;
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>_contentViewController 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: #0000ff;">@end</span></pre>
<p>The first interesting code is to setup the view that is managed by our toolbar controller. This view have two subviews, a <code>UIToolbar</code>, and a view that we fetch from the content view controller we where given. We do this setup in the <code>loadView</code> method.</p>
<pre class="objc">- <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>loadView;
<span style="color: #002200;">&#123;</span>
    UIView* contentView = _contentViewController.view;
    CGRect frame = contentView.frame;
    UIView* view = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIView alloc<span style="color: #002200;">&#93;</span> initWithFrame:frame<span style="color: #002200;">&#93;</span>;
&nbsp;
    frame = CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">0</span>, frame.size.width, frame.size.height - <span style="color: #0000dd;">44</span>.0f<span style="color: #002200;">&#41;</span>;
    contentView.frame = frame;
    <span style="color: #002200;">&#91;</span>view addSubview:contentView<span style="color: #002200;">&#93;</span>;
&nbsp;
    frame = CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #0000dd;">0</span>.0f, frame.size.height, frame.size.width, <span style="color: #0000dd;">44</span>.0f<span style="color: #002200;">&#41;</span>;
    _toolbar = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIToolbar alloc<span style="color: #002200;">&#93;</span> initWithFrame:frame<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>view addSubview:_toolbar<span style="color: #002200;">&#93;</span>;
&nbsp;
    self.view = view;
    <span style="color: #002200;">&#91;</span>view release<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>_toolbar release<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>This code reuses the screen setup already done by the content view controller, and re-layouts our subviews. It is a simple solution, and you will need a custom class for the root view with an overloaded <code>layoutSubviews</code> if you want to properly handle orientation changes. But I have left this out, as it is not within the scope of this post.</p>
<p>Next up we need to update the toolbar with contextual toolbar items, when our content changes. This is only supported if the content view controller is a <code>UINavigationController</code>, as can be seen in the initializer above. This could be made more flexible, but is also outside the scope of this post. We have set our toolbar controller to be the delegate for the content navigation view controller, so all we need to do is to respond to navigation events as they occur. </p>
<pre class="objc">- <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>navigationController:<span style="color: #002200;">&#40;</span>UINavigationController *<span style="color: #002200;">&#41;</span>navigationController
        willShowViewController:<span style="color: #002200;">&#40;</span>UIViewController *<span style="color: #002200;">&#41;</span>viewController
        animated:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>animated;
<span style="color: #002200;">&#123;</span>
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>* items = <span style="color: #0000ff;">nil</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>viewController respondsToSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>toolbarItems<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        items = <span style="color: #002200;">&#91;</span>viewController performSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>toolbarItems<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#91;</span>_toolbar setItems:items animated:animated<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<h3>Conclusion</h3>
<p>As shown with this code, doing the correct way with Cocoa Touch almost always means doing it in the easiest way as well. The hard part is knowing what the correct way is. My hope is that this post can guide you in the right direction. Rule of thumb is to always try to follow the same pattern as similiar things in Cocoa, it might feel like it is harder to do, but at the end of the day you will end up with less code, with more features.</p>
<p>The code above for implementing the custom toolbar controller, is much less code than what is needed to write a small application to demonstrate it being used. I have therefor made a small demonstration application with this complete code. It is a tree of table views, where each item opens up a new table view tree with one less toolbar item. </p>
<p>The source code is released under BSD license, and you can <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/toolbarapp.zip">download it here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/22/uitoolbars-in-iphone-os-2x/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Proxy Based AOP for Cocoa Touch</title>
		<link>http://blog.jayway.com/2009/03/06/proxy-based-aop-for-cocoa-touch/</link>
		<comments>http://blog.jayway.com/2009/03/06/proxy-based-aop-for-cocoa-touch/#comments</comments>
		<pubDate>Fri, 06 Mar 2009 14:46:33 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[proxy]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1041</guid>
		<description><![CDATA[UITabBarController is generally used as is, no subclassing required. It creates a UITabBar and manages a list of UIViewControllers, keeping track of the tab in focus, UI creation and everything nice. UITabBarController has a delegate, the UITabBarControllerDelegate protocol. Unfortunately this is not a superset of the UITabBarDelegate protocol, and UITabBarController already implements the UITabBarDelegate protocol [...]]]></description>
			<content:encoded><![CDATA[<p><code>UITabBarController</code> is generally used as is, no subclassing required. It creates a <code>UITabBar</code> and manages a list of <code>UIViewControllers</code>, keeping track of the tab in focus, UI creation and everything nice. <code>UITabBarController</code> has a delegate, the <code>UITabBarControllerDelegate</code> protocol. Unfortunately this is not a superset of the <code>UITabBarDelegate</code> protocol, and <code>UITabBarController</code> already implements the <code>UITabBarDelegate</code> protocol itself. So how can I hook into and respond to delegate calls from the managed <code>UITabBar</code>?</p>
<p>Simply replacing the original delegate will break the default functionality. We need to somehow insert our own code to execute before the original delegates call. Or in AOP speak; a before advice.</p>
<h3>The Wanted Solution</h3>
<p>What we want is a proxy that can forward invocations both to our own delegate, and to the original delegate. The interface for said class looks looks like this:</p>
<pre class="objc"><span style="color: #0000ff;">@protocol</span> CWDelegateOverrideProxyDelegate
@required
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>shouldCallOriginalImplementationForSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
<span style="color: #0000ff;">@end</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> CWDelegateOverrideProxy : <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSProxy.html"><span style="color: #0000ff;">NSProxy</span></a> <span style="color: #002200;">&#123;</span>
<span style="color: #0000ff;">@private</span>
  id&lt;NSObject&gt; _originalDelegate;
  id&lt;NSObject&gt; _overrideingDelegate;
  id&lt;CWDelegateOverrideProxyDelegate&gt; _delegate;
<span style="color: #002200;">&#125;</span>
&nbsp;
@property<span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> id&lt;NSObject&gt; originalDelegate;
@property<span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> id&lt;NSObject&gt; overridingDelegate;
@property<span style="color: #002200;">&#40;</span>nonatomic, assign<span style="color: #002200;">&#41;</span> id&lt;CWDelegateOverrideProxyDelegate&gt; delegate;
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>initWithOriginalDelegate:<span style="color: #002200;">&#40;</span>id&lt;NSObject&gt;<span style="color: #002200;">&#41;</span>originalDelegate
     overridingDelegate:<span style="color: #002200;">&#40;</span>id&lt;NSObject&gt;<span style="color: #002200;">&#41;</span>overridingDelegate;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>And then we could use this class to replace an existing delegate with a short piece fo code like this:</p>
<pre class="objc">UITabBar* tabBar = <span style="color: #002200;">&#40;</span>UITabBar*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span>self.tabBarController.view
    viewWithKindOfClass:<span style="color: #002200;">&#91;</span>UITabBar <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
CWDelegateOverrideProxy* proxy = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CWDelegateOverrideProxy alloc<span style="color: #002200;">&#93;</span>
    initWithOriginalDelegate:tabBar.delegate overridingDelegate:self<span style="color: #002200;">&#93;</span>;
tabBar.delegate = <span style="color: #002200;">&#40;</span>id&lt;UITabBarDelegate&gt;<span style="color: #002200;">&#41;</span>proxy;</pre>
<p>See <a href="http://blog.jayway.com/2009/02/24/finding-subview-of-a-particular-class-in-cocoa/">my previous post</a> for the implementation of <code>viewWithKindOfClass:</code>.</p>
<p>Easy enough to use, only thing left is to implement <code>CWDelegateOverrideProxy</code>.</p>
<h3>Enter <code>NSProxy</code></h3>
<p>Java only have one root class; <code>java.lang.Object</code>. Objective-C can have many, and Cocoa defines two; <code>NSObject</code> and <code>NSProxy</code>. Both of them conforms to the protocol <code>NSObject</code>, wich can be confusing. What we need to know is that class names, and protocol names have two different name spaces in Objective-C. Imagine it as if you could have a class and an interface with the same name in Java; in Objective-C you can. <code>NSObject</code> class is the root class for all concrete classes, and <code>NSProxy</code> class is the root class for proxies, both implements <code>NSObject</code> protocol allowing them to be interchangeable.</p>
<p>Without much ado, here is the base implementation for the initializer:</p>
<pre class="objc"><span style="color: #339900;">#import &quot;CWDelegateOverrideProxy.h&quot;</span>
&nbsp;
<span style="color: #0000ff;">@implementation</span> CWDelegateOverrideProxy
&nbsp;
@synthesize originalDelegate = _originalDelegate;
@synthesize overridingDelegate = _overridingDelegate;
@synthesize delegate = _delegate;
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>initWithOriginalDelegate:<span style="color: #002200;">&#40;</span>id&lt;NSObject&gt;<span style="color: #002200;">&#41;</span>originalDelegate
     overridingDelegate:<span style="color: #002200;">&#40;</span>id&lt;NSObject&gt;<span style="color: #002200;">&#41;</span>overridingDelegate;
<span style="color: #002200;">&#123;</span>
  _originalDelegate = <span style="color: #002200;">&#91;</span>originalDelegate retain<span style="color: #002200;">&#93;</span>;
  _overridingDelegate = <span style="color: #002200;">&#91;</span>overridingDelegate retain<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #ff0000;">// More code goes here!</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3>Introspection</h3>
<p>In Objective-C, just as in Java, an instance can be queried for its class, and conformance to protocols (interface in Java speak). But as a bonus an instance can also be queried for specific methods per instance.</p>
<p>Our <code>CWDelegateOverrideProxy</code> class inherits from <code>NSProxy</code>. And it makes a simple assumption; if the original delegate, or the overriding delegate is capable of something, then so it is. So if queried for type of class, protocol conformance, or implemented methods, then we reply with whatever our managed delegates replies.</p>
<p>The <code>NSObject</code> protocol defines methods, equivalent of the <code>java.lang.reflect</code> package, that allows us to implement this as such:</p>
<pre class="objc"><span style="color: #339900;">#pragma mark --- Testing Object Behavior, and Conformance</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>isKindOfClass:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">Class</span><span style="color: #002200;">&#41;</span>aClass;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.overridingDelegate isKindOfClass:aClass<span style="color: #002200;">&#93;</span> ||
         <span style="color: #002200;">&#91;</span>self.originalDelegate isKindOfClass:aClass<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>conformsToProtocol:<span style="color: #002200;">&#40;</span>Protocol *<span style="color: #002200;">&#41;</span>aProtocol;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.overridingDelegate conformsToProtocol:aProtocol<span style="color: #002200;">&#93;</span> ||
         <span style="color: #002200;">&#91;</span>self.originalDelegate conformsToProtocol:aProtocol<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>respondsToSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.overridingDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span> ||
         <span style="color: #002200;">&#91;</span>self.originalDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<h3>Invocation Forwarding</h3>
<p>The <code>NSObject</code> protocol also defines methods for functionality equivalent of <code>java.lang.reflect.InvocationHandler</code> and hooks to act as a <code>java.lang.reflect.Proxy</code>. The details are different as Objective-C do not enforce calls to only known methods at compile time, which means that at run-time unimplemented methods can be called.</p>
<p>When an unimplemented method is called the run-time will call <code>methodSignatureForSelector:</code>, that can return a <code>NSMethodSignature</code> instance, sort of the equivalent of a <code>java.lang.reflect.Method</code>. The run-time will then use the information from the <code>NSMethodSignature</code> instance to create a correct <code>NSInvocation</code> (other half of a <code>java.lang.reflect.Method</code>) instance, and set the correct arguments. This NSInvocation instance is then used as argument to call <code>forwardInvocation:</code>.</p>
<p>And thus our implementation is completed with:</p>
<pre class="objc"><span style="color: #339900;">#pragma mark --- Handling Proxy Methods</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMethodSignature.html"><span style="color: #0000ff;">NSMethodSignature</span></a>*<span style="color: #002200;">&#41;</span>methodSignatureForSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>self.overridingDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.overridingDelegate methodSignatureForSelector:aSelector<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>self.originalDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.originalDelegate methodSignatureForSelector:aSelector<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>super methodSignatureForSelector:aSelector<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>forwardInvocation:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSInvocation.html"><span style="color: #0000ff;">NSInvocation</span></a>*<span style="color: #002200;">&#41;</span>anInvocation;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">BOOL</span> shouldCallOriginal = YES;
  <span style="color: #0000ff;">SEL</span> aSelector = <span style="color: #002200;">&#91;</span>anInvocation selector<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>self.overridingDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>anInvocation setTarget:self.overridingDelegate<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>anInvocation invoke<span style="color: #002200;">&#93;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>self.delegate != <span style="color: #0000ff;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      shouldCallOriginal = <span style="color: #002200;">&#91;</span>self.delegate shouldCallOriginalImplementationForSelector:aSelector<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>shouldCallOriginal &amp;&amp; <span style="color: #002200;">&#91;</span>self.originalDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>anInvocation setTarget:self.originalDelegate<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>anInvocation invoke<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre>
<p>And that rounds up how to implement a class that handles proxy based AOP, in order to introduce a before advice for delegate methods. For a more complex code base you can look at <a href="http://sourceforge.net/projects/hessiankit/">HessianKit</a>, a framework that uses proxies, invocation forwarding and dynamic class creation in order to use a web service as distributed objects.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/06/proxy-based-aop-for-cocoa-touch/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Finding Subview of a Particular Class in Cocoa</title>
		<link>http://blog.jayway.com/2009/02/24/finding-subview-of-a-particular-class-in-cocoa/</link>
		<comments>http://blog.jayway.com/2009/02/24/finding-subview-of-a-particular-class-in-cocoa/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 16:52:17 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1008</guid>
		<description><![CDATA[Many of the UIView subclasses in Cocoa, and especially Cocoa Touch are created by combining many different simple views into a more complex view. UITableViewCell is a good example, concisting of almost a dozen subviews, UIImageView for the image, UILabel for the text, etc. It is often nice to be able to reuse existing functionality [...]]]></description>
			<content:encoded><![CDATA[<p>Many of the <code>UIView</code> subclasses in Cocoa, and especially Cocoa Touch are created by combining many different simple views into a more complex view. <code>UITableViewCell</code> is a good example, concisting of almost a dozen subviews, <code>UIImageView</code> for the image, <code>UILabel</code> for the text, etc.</p>
<p>It is often nice to be able to reuse existing functionality when you subclass <code>UITableViewCell</code>. Properties such as image and <code>textColor</code> maps directly to the embedded <code>UILabel</code> and <code>UIImageView</code> subviews, and reimplementing them all when introducing a custom layout is tedious and error prone. Would it not be better to be able to get access to the original subview instances and just add a custom layout to them?</p>
<h3>You can find subviews by class</h3>
<p>Would it not be nice if the Cocoa Touch framework had a method such as this:</p>
<pre class="objc">- <span style="color: #002200;">&#40;</span>UIView*<span style="color: #002200;">&#41;</span>viewWithKindOfClass:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">Class</span><span style="color: #002200;">&#41;</span>aClass;</pre>
<p>Kind of like what <code>viewWithTag:</code>, does but instead of searching for a subview matching a tag, it searches for a subview matching a class.</p>
<p>Good news for us is that this is very easy to implement, by just adding a new category to <code>UIView</code>. Add a new .h/.m file pair to your Xcode project and type this down in the header file:</p>
<pre class="objc"><span style="color: #339900;">#import &lt;UIKit/UIKit.h&gt;</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> UIView <span style="color: #002200;">&#40;</span>CWViewWithKindOfClass<span style="color: #002200;">&#41;</span>
&nbsp;
- <span style="color: #002200;">&#40;</span>UIView*<span style="color: #002200;">&#41;</span>viewWithKindOfClass:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">Class</span><span style="color: #002200;">&#41;</span>aClass;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>Now we have to implement it. The existing <code>viewWithTag:</code> method is not documented as such, but my experimentation tells me that it uses a breadth first search algorithm. Quite logical as the wanted subview most commonly is close to the root view, and we want to find it fast. Since <code>viewWithTag:</code> always returns the first found matching view, we can do the same assumption.</p>
<p>The quite short implementation goes like this:</p>
<pre class="objc"><span style="color: #339900;">#import &quot;UIView+CWViewWithKindOfClass.h&quot;</span>
&nbsp;
<span style="color: #0000ff;">@implementation</span> UIView <span style="color: #002200;">&#40;</span>CWViewWithKindOfClass<span style="color: #002200;">&#41;</span>
&nbsp;
- <span style="color: #002200;">&#40;</span>UIView*<span style="color: #002200;">&#41;</span>viewWithKindOfClass:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">Class</span><span style="color: #002200;">&#41;</span>aClass;
<span style="color: #002200;">&#123;</span>
  <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMutableArray.html"><span style="color: #0000ff;">NSMutableArray</span></a>* nodeQueue = <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMutableArray.html"><span style="color: #0000ff;">NSMutableArray</span></a> arrayWithObject:self<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">while</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>nodeQueue count<span style="color: #002200;">&#93;</span> &gt; <span style="color: #0000dd;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    UIView* node = <span style="color: #002200;">&#91;</span>nodeQueue objectAtIndex:<span style="color: #0000dd;">0</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>nodeQueue removeObjectAtIndex:<span style="color: #0000dd;">0</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>node isKindOfClass:aClass<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      <span style="color: #0000ff;">return</span> node;
    <span style="color: #002200;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #002200;">&#123;</span>
      <span style="color: #002200;">&#91;</span>nodeQueue addObjectsFromArray:node.subviews<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">nil</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>And that is it, not you can use it with something like for example this:</p>
<pre class="objc">UITabBar* tabBar = <span style="color: #002200;">&#91;</span>myTabBarController.view viewWithKindOfClass:<span style="color: #002200;">&#91;</span>UITabBar <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;</pre>
<p>Wich is an introduction to a future post, where I will discuss how to access the managed <code>UITabBar</code> of a <code>UITabBarController</code>, and introduce a <code>UITabBarDelegate</code> without interfering with the delegate already in place from the Cocoa Touch framework.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/02/24/finding-subview-of-a-particular-class-in-cocoa/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>UIButton troubles, a better solution</title>
		<link>http://blog.jayway.com/2008/12/17/uibutton-troubles-a-better-solution/</link>
		<comments>http://blog.jayway.com/2008/12/17/uibutton-troubles-a-better-solution/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 17:10:33 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=651</guid>
		<description><![CDATA[I described in my previous post how you can change the class of a live object instance. The use-case was a workaround for bug in Cocoa Touch's UIKit. What if I could fix the bug, instead of applying a work around in my sub-class? Update: Buttons created with UIButtonTypeRoundedRect is a special case returning a [...]]]></description>
			<content:encoded><![CDATA[<p>I described in my <a href="http://blog.jayway.com/2008/12/12/uibutton-troubles-and-obj-c-magic/">previous post</a> how you can change the class of a live object instance. The use-case was a workaround for bug in Cocoa Touch's UIKit. What if I could fix the bug, instead of applying a work around in my sub-class?</p>
<p><strong>Update:</strong> Buttons created with <code>UIButtonTypeRoundedRect</code> is a special case returning a private subclass of <code>UIButton</code>, this bugfix can therefor not safely be used with rounded buttons. Good news is that they already have a large nice touch area.</p>
<h3>With Objective-C you can</h3>
<p>In short the problem is that the implementation of the factory method <code>buttonWithType:</code> in <code>UIButton</code> do not respect subclasses, so it will always return instances of <code>UIButton</code>. This is bad since it is the only method available to use to get custom buttons. Without access to the source code for <code>UIButton</code> changes can not be made to the implementation, so in order to fix the bug in UIKit we must wrap the original implementation of <code>buttonWithType:</code> with our own method that applies the bugfix. </p>
<p>Adding a category with a new implementation will not work, since that would shadow the original implementation. What is need is some sort of <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">AOP</a>, and Objective-C gives us enough of this but under the name of <a href="http://www.cocoadev.com/index.pl?MethodSwizzling">method-swizzling</a>.</p>
<p>We can intercept method calls to <code>buttonWithType</code>: by swizzling the implementation with the implementation of our own method. In Objective-C all method implementations are called by name, that name is what is know as a selector. By swizzling the implementations we can make messages with the old selector call our new implementation, and vice versa.</p>
<p>We do this by adding a category to UIButton with this class method:</p>
<pre class="objc"><span style="color: #339900;">#import &lt;objc/runtime.h&gt;</span>
+<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>load;
<span style="color: #002200;">&#123;</span>
  Method oldMethod = class_getClassMethod<span style="color: #002200;">&#40;</span>self, <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>buttonWithType:<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
  Method newMethod = class_getClassMethod<span style="color: #002200;">&#40;</span>self, <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>__buttonWithType:<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
  method_exchangeImplementations<span style="color: #002200;">&#40;</span>oldMethod, newMethod<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>The class method <code>load</code> is called once for each class and category as they are loaded into the run-time, and is the optimal place to add initialization code. Think of it as static initializer blocks in Java.</p>
<p>And that is it, apart from implementing the actual bugfix in our <code>__buttonWithType:</code> method.</p>
<h3>A better bugfix</h3>
<p>The fix I did in my previous post only worked if the new subclass of <code>UIBUtton</code> did not introduce any new instance variables. This is a limitation, and not quite as obvious to new users of our bugfix, so this time around the bugfix will work with any subclass.</p>
<p>The trick here is allocate a new instance of the correct subclass if needed, and copy over the instance variables. Implementation:</p>
<pre class="objc">+<span style="color: #002200;">&#40;</span>UIButton*<span style="color: #002200;">&#41;</span>__buttonWithType:<span style="color: #002200;">&#40;</span>UIButtonType<span style="color: #002200;">&#41;</span>type;
<span style="color: #002200;">&#123;</span>
  UIButton* button = <span style="color: #002200;">&#91;</span>self __buttonWithType:type<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">Class</span> buttonClass = <span style="color: #002200;">&#91;</span>button <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>button &amp;&amp; buttonClass != self &amp;&amp; buttonClass == <span style="color: #002200;">&#91;</span>UIButton <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #0000ff;">size_t</span> oldSize = class_getInstanceSize<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>button <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">size_t</span> newSize = class_getInstanceSize<span style="color: #002200;">&#40;</span>self<span style="color: #002200;">&#41;</span>;
    button-&gt;isa = self;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>oldSize &lt; newSize<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      UIButton* newButton = <span style="color: #002200;">&#91;</span>self alloc<span style="color: #002200;">&#93;</span>;
      <a href="http://www.opengroup.org/onlinepubs/009695399/functions/memcpy.html"><span style="color: #0000dd;">memcpy</span></a><span style="color: #002200;">&#40;</span>newButton, button, oldSize<span style="color: #002200;">&#41;</span>;
      button = <span style="color: #002200;">&#91;</span>newButton autorelease<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> button;
<span style="color: #002200;">&#125;</span></pre>
<p>At first glance the first statement might look like a recursive call, but remember that we have swizzled the implementations so it will call the original implementation of <code>buttonWithType:</code>.</p>
<p>Also note that we must autorelease the new instance that we allocated, and that we must not release the original instance as that one is already owned by an auto release pool.</p>
<p>And that is how you go about fixing bugs in Objective-C for code that you do not have access to the source code for.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/17/uibutton-troubles-a-better-solution/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>UIButton troubles, and Obj-C magic</title>
		<link>http://blog.jayway.com/2008/12/12/uibutton-troubles-and-obj-c-magic/</link>
		<comments>http://blog.jayway.com/2008/12/12/uibutton-troubles-and-obj-c-magic/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 14:54:56 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=557</guid>
		<description><![CDATA[When developing SC68 Player for the iPhone I came upon a quite peculiar problem regarding the UIButton. First the preface I wanted to add a star button to the right side of each row, subclassing UIButton that can manage selected states, images and all I needed, and use it as the accessory view of the [...]]]></description>
			<content:encoded><![CDATA[<p>When developing <a href="http://www.peylow.se/sc68player.html">SC68 Player</a> for the iPhone I came upon a quite peculiar problem regarding the <code>UIButton</code>. </p>
<h3>First the preface</h3>
<p>I wanted to add a star button to the right side of each row, subclassing UIButton that can manage selected states, images and all I needed, and use it as the accessory view of the <code>UITableViewCell</code> felt natural. It works and is the right thing to do. The simple factory method is:</p>
<pre class="objc">+<span style="color: #002200;">&#40;</span>CWFavouritesButton*<span style="color: #002200;">&#41;</span>favouritesButtonWithTarget:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>target action:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>action;
<span style="color: #002200;">&#123;</span>
  CWFavouritesButton* button = <span style="color: #002200;">&#91;</span>self buttonWithType:UIButtonTypeCustom<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>button<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside<span style="color: #002200;">&#93;</span>;
    button.frame = CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">29</span>, <span style="color: #0000dd;">31</span><span style="color: #002200;">&#41;</span>;
    button.backgroundColor = <span style="color: #002200;">&#91;</span>UIColor clearColor<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>button setImage:<span style="color: #002200;">&#91;</span>UIImage imageNamed:@<span style="color: #666666;">&quot;star-deselected.png&quot;</span><span style="color: #002200;">&#93;</span> forState:UIControlStateNormal<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>button setImage:<span style="color: #002200;">&#91;</span>UIImage imageNamed:@<span style="color: #666666;">&quot;star-selected.png&quot;</span><span style="color: #002200;">&#93;</span> forState:UIControlStateSelected<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> button;
<span style="color: #002200;">&#125;</span></pre>
<p>Now if this had been all then, simply adding the factory method with a category on <code>UIButton</code> would have been enough. But as it is, a <code>UIButton</code> uses the alpha mask of its' image as hit target. That hit target is quite small, at least 44 pixels should be used with fingers on a touch screen. Therefor I subclass <code>UIButton</code> so that I can override the hit test as this:</p>
<pre class="objc">-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>pointInside:<span style="color: #002200;">&#40;</span>CGPoint<span style="color: #002200;">&#41;</span>point withEvent:<span style="color: #002200;">&#40;</span>UIEvent *<span style="color: #002200;">&#41;</span>event;
<span style="color: #002200;">&#123;</span>
  CGRect bounds = self.bounds;
  bounds = CGRectInset<span style="color: #002200;">&#40;</span>bounds, <span style="color: #0000dd;">-32</span>, <span style="color: #0000dd;">0</span><span style="color: #002200;">&#41;</span>;
  <span style="color: #0000ff;">return</span> CGRectContainsPoint<span style="color: #002200;">&#40;</span>bounds, point<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>This would allow for an extra 32 pixels to hit on the left and right side of my star button. But now problems arise! Turns out that the overridden implementation of <code>pointInside:withEvent:</code> is never called.</p>
<p>Many hours of troubleshooting later I figured out that the <code>buttonWithType:</code> factory method is the culprit; it do not respect subclasses. Meaning that it will always return instances of <code>UIButton</code>, and thus always call the original implementation of <code>pointInside:withEvent:</code>. Unfortunetely this is the only public factory or init method that can be used to create a button with images only. What to do?</p>
<h3>Objective-C to the rescue</h3>
<p>With Objective-C we can change the class of an already live object instance, one nice feature of having a dynamic run-time.</p>
<p>All books will tell you that all classes inherits from <code>NSObject</code>. This is not quite true, there is among others <code>NSProxy</code> as well, and you could actually introduce your own root classes if you like. All of them will inherit from the run-time class <code>id</code>. The run-time class <code>id</code> do not implement a single class method, nor instance methods, all it has is a single instance variable: <code>isa</code> of type <code>Class</code>.</p>
<p>As we all should know classes in Objective-C are also object instances, instances of their meta-classes. The <code>isa</code> instance variable is the reference to the object instance's class instance. And here is the gold nugget; it is write-able. So we can change an object instance's class by simply assigning a new value to <code>isa</code>.</p>
<p>So lets update the previous factory method to this:</p>
<pre class="objc">+<span style="color: #002200;">&#40;</span>CWFavouritesButton*<span style="color: #002200;">&#41;</span>favouritesButtonWithTarget:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>target action:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>action;
<span style="color: #002200;">&#123;</span>
  CWFavouritesButton* button = <span style="color: #002200;">&#91;</span>self buttonWithType:UIButtonTypeCustom<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>button<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    button-&gt;isa = <span style="color: #002200;">&#91;</span>CWFavouritesButton <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #ff0000;">// More init code...</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> button;
<span style="color: #002200;">&#125;</span></pre>
<h3>Some precaution</h3>
<p>This might look dangerous, and it is. But not so dangerous that you should shun it, the Cocoa frameworks uses it to it's advantage, and so should you. The only thing you need to be aware of is that the instance size of the original and new classes must be the same. This is easily done by importing <code>runtime.h</code>, and use <code>class_getInstanceSize()</code>.</p>
<pre class="objc"><span style="color: #339900;">#import &lt;objc/runtime.h&gt;</span>
+<span style="color: #002200;">&#40;</span>CWFavouritesButton*<span style="color: #002200;">&#41;</span>favouritesButtonWithTarget:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>target action:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>action;
<span style="color: #002200;">&#123;</span>
  CWFavouritesButton* button = <span style="color: #002200;">&#91;</span>self buttonWithType:UIButtonTypeCustom<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>button &amp;&amp; <span style="color: #002200;">&#40;</span>class_getInstanceSize<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>button <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> == class_getInstanceSize<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>CWFavouritesButton <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    button-&gt;isa = <span style="color: #002200;">&#91;</span>CWFavouritesButton <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #ff0000;">// More init code...</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> button;
<span style="color: #002200;">&#125;</span></pre>
<p>And finally our factory method safely return a new button of the correct subclass, and <code>pointInside:withEvent:</code> is called as expected.</p>
<p>The full source code for SC68 Player where I implemented this is available for <a href="http://www.peylow.se/SC68Player101_src.zip">download here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/12/uibutton-troubles-and-obj-c-magic/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Accelerometer and Vibration on the iPhone</title>
		<link>http://blog.jayway.com/2008/11/25/accelerometer-and-vibration-on-the-iphone/</link>
		<comments>http://blog.jayway.com/2008/11/25/accelerometer-and-vibration-on-the-iphone/#comments</comments>
		<pubDate>Tue, 25 Nov 2008 07:48:47 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[accelerometer]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[oredev]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=464</guid>
		<description><![CDATA[Last friday I attended an excellent session at Øredev 2008, on Android by Mike Jennings from Google. At the end of the presentation Mike show the code for a simple application with a bouncing blue ball, controlled by the accelerometer. What stroke me was that the git of the application was 85 lines of code, [...]]]></description>
			<content:encoded><![CDATA[<p>Last friday I attended an excellent session at <a href="http://www.oredev.org">Øredev 2008</a>, on <a href="http://code.google.com/android/">Android</a> by Mike Jennings from Google. At the end of the presentation Mike show the code for a simple application with a bouncing blue ball, controlled by the accelerometer. What stroke me was that the git of the application was 85 lines of code, and Mike told us most of the physics and life cycle code was hidden away. I have never used the accelerometer on the iPhone, but my gut told me that 85 lines was allot of code.</p>
<p>So I took out my laptop during the next 60 minutes of Panel Debate, and wrote an iPhone app, and as I expected the code landed on 46 lines of code for the actual application logic, physics, grits and all. Or 112 lines of code if headers and boiler-plate should be counted as well.</p>
<p>This blog post will describe what I did, in a quite nice model-view-controller fashion <em>(Model and Controller is implemented in the same class)</em>.</p>
<ul>
<li>First of all I needed a view to display my bouncing ball on, I choose to subclass UIViewController to handle this view.</li>
<li>A standard UIView instance with a UIImageView sub-view for the ball is all I need for my view, this I setup using Interface Builder.</li>
<li>And the model/logic is handled by one CGPoint for the current location, and one CGPoint with the current delta movement of the ball.</li>
</ul>
<p>First the custom view controller sets up itself as the accelerometer delegate when awakening from it's nib-file.</p>
<pre class="objc">-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>awakeFromNib;
<span style="color: #002200;">&#123;</span>
  self.location = CGPointMake<span style="color: #002200;">&#40;</span><span style="color: #0000dd;">160</span>, <span style="color: #0000dd;">230</span><span style="color: #002200;">&#41;</span>;
  UIAccelerometer* accelerometer = <span style="color: #002200;">&#91;</span>UIAccelerometer sharedAccelerometer<span style="color: #002200;">&#93;</span>;
  accelerometer.updateInterval = <span style="color: #0000dd;">0.02</span>;
  accelerometer.delegate = self;
<span style="color: #002200;">&#125;</span></pre>
<p>Then comes a private function for the <em>quite faked physics</em>, it is responsible for detecting if a value with a given delta movement has hit a min or max edge. If it do hits an edge, it flips it's delta movement with some deceleration, and corrects it's value.</p>
<pre class="objc"><span style="color: #0000ff;">static</span> inline <span style="color: #0000ff;">BOOL</span> bounce<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">float</span>* val, <span style="color: #0000ff;">float</span>* delta, <span style="color: #0000ff;">float</span> min, <span style="color: #0000ff;">float</span> max<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
<span style="color: #339900;">#define FLIP(val, c) (c - (val - c))</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>*val &lt; min || *val &gt; max<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    *delta = -<span style="color: #002200;">&#40;</span>*delta * <span style="color: #0000dd;">0.75</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">float</span> loc = *val &lt; min ? min : max;
    *val = FLIP<span style="color: #002200;">&#40;</span>*val, loc<span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">return</span> YES;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> NO;
<span style="color: #002200;">&#125;</span></pre>
<p>And lastly the delegate method that is called by the accelerometer. Here we update the delta movement, and use the bounce-function to detect and compensate location+delta when the ball hits any edges. If an edge it hit, a vibration is also triggered.</p>
<pre class="objc">-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>accelerometer:<span style="color: #002200;">&#40;</span>UIAccelerometer*<span style="color: #002200;">&#41;</span>accelerometer
       didAccelerate:<span style="color: #002200;">&#40;</span>UIAcceleration*<span style="color: #002200;">&#41;</span>acceleration;
<span style="color: #002200;">&#123;</span>
<span style="color: #339900;">#define CAP(val, max) (val &lt; -max ? -max : (val &gt; max ? max : val))</span>
  CGPoint delta = CGPointMake<span style="color: #002200;">&#40;</span>CAP<span style="color: #002200;">&#40;</span>self.delta.x + acceleration.x, <span style="color: #0000dd;">32</span><span style="color: #002200;">&#41;</span>,
                              CAP<span style="color: #002200;">&#40;</span>self.delta.y - acceleration.y, <span style="color: #0000dd;">32</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
  CGPoint location = CGPointMake<span style="color: #002200;">&#40;</span>self.location.x + delta.x,
                                 self.location.y + delta.y<span style="color: #002200;">&#41;</span>;
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>bounce<span style="color: #002200;">&#40;</span>&amp;location.x, &amp;delta.x, <span style="color: #0000dd;">8</span>, self.view.bounds.size.width - <span style="color: #0000dd;">8</span> <span style="color: #002200;">&#41;</span> ||
      bounce<span style="color: #002200;">&#40;</span>&amp;location.y, &amp;delta.y, <span style="color: #0000dd;">8</span>, self.view.bounds.size.height - <span style="color: #0000dd;">8</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>
  <span style="color: #002200;">&#123;</span>
      AudioServicesPlayAlertSound<span style="color: #002200;">&#40;</span>kSystemSoundID_Vibrate<span style="color: #002200;">&#41;</span>;
  <span style="color: #002200;">&#125;</span>
  self.delta = delta;
  self.location = location;
  self.ballView.center = self.location;
<span style="color: #002200;">&#125;</span></pre>
<p>In conclusion Cocoa Touch requires surprisingly little code for accessing and using the accelerometer and trigger a vibration. Triggering a vibration is literary done with a single line of code. The lines of code needed to setup and listen to the accelerometer can literary be counted on the fingers of one hand.</p>
<p>On the downside there is no finer control of the vibration, and if you like to have the rotation angles of the device instead of simple gravity forces of the x, y and z axis, then you must do the math for yourself. Simple enough, but it would had been nice to have to current rotations around each axis as well. </p>
<p>The full source code can be downloaded <a href="http://www.peylow.se/BouncyBall.zip">here</a>.</p>
<p>ps. I dare Mike Jennings to best this <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . ds.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/11/25/accelerometer-and-vibration-on-the-iphone/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>HessianKit Released</title>
		<link>http://blog.jayway.com/2008/07/10/hessiankit-released/</link>
		<comments>http://blog.jayway.com/2008/07/10/hessiankit-released/#comments</comments>
		<pubDate>Thu, 10 Jul 2008 09:04:04 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[hessian]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[webservice]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=268</guid>
		<description><![CDATA[HessianKit, an implementation of the Hessian binary web service protocol for Objective-C 2.0 have now been released under Apache License 2. It is available on sourceforge at: http://sourceforge.net/projects/hessiankit HessianKit is available for Mac OS X 10.5 and later, and iPhone OS 2.0. The three main goals are: * To be as compliant and forgiving as [...]]]></description>
			<content:encoded><![CDATA[<p>HessianKit, an implementation of the <a href="http://hessian.caucho.com/">Hessian binary web service protocol</a> for Objective-C 2.0 have now been released under Apache License 2. It is available on sourceforge at:<br />
<a href="http://sourceforge.net/projects/hessiankit/">http://sourceforge.net/projects/hessiankit</a></p>
<p>HessianKit is available for Mac OS X 10.5 and later, and iPhone OS 2.0. The three main goals are:<br />
* To be as compliant and forgiving as possible.<br />
* Provide seamless Objective-C experience against web services implemented in Java.<br />
* Avoid glue-code.</p>
<p>This is done by allowing clients to define proxy and value object as Objective-C protocols, and let HessianKit generate conforming classes on the fly. HessianKit is design to be similar to Distributed Objects in Mac OS X Cocoa (not available for iPhone OS). Re-inventing the wheel is avoided by building on available technology in Cocoa (Touch) such as key-value-coding, introspection, and invocation forwarding.</p>
<p>HessianKit is currently 1.0beta, but is production ready, and is used for implementing iPhone clients for web services previously designed for JavaME applications.</p>
<p>So how does it work? Lets assume we have a hessian web service publishing the following Java interface:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> HelloService <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> helloWorld<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>The Objective-C implementation would then need to define the same Java interface as an Obj-C protocol.</p>
<pre class="objc">&nbsp;
<span style="color: #0000ff;">@protocol</span> CWHelloService
-<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>*<span style="color: #002200;">&#41;</span>helloWorld;
<span style="color: #0000ff;">@end</span></pre>
<p>With the interface/protocol defined the client creates proxies to the web service as follows.</p>
<pre class="objc">&nbsp;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSURL.html"><span style="color: #0000ff;">NSURL</span></a>* url = <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSURL.html"><span style="color: #0000ff;">NSURL</span></a> URLWithString@<span style="color: #666666;">&quot;http://www.mydomain.com/helloservice&quot;</span><span style="color: #002200;">&#93;</span>;
id&amp;lt;CWHelloService&amp;gt; proxy = <span style="color: #002200;">&#40;</span>id&amp;lt;CWHelloService&amp;gt;<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span>CWHessianConnection proxyWithURL:url protocol:<span style="color: #0000ff;">@protocol</span><span style="color: #002200;">&#40;</span>CWHelloService<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
NSLog<span style="color: #002200;">&#40;</span>@<span style="color: #666666;">&quot;hello: %@&quot;</span>, <span style="color: #002200;">&#91;</span>proxy helloWorld<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;</pre>
<p>And that is it.</p>
<p>Since Java and Objective-C differ in the naming of methods, some translation must be done when sending call tho the hessian web service. Method names are first looked up using the class method CWHessianArchiver methodNameForSelector:], if a method name is not returned, the method name to use will be generated to match Java and Obj-C conventions as closely as possible. Some examples.</p>
<pre>doFoo      ==>  doFoo
getFoo:    ==>  getFoo__1
doFoo:bar: ==>  doFooBar__2
doFugly::: ==>  doFugly__3</pre>
<p>Data will be serialized using standard Hessian types; boolean, int, and double. All Obj-C classes that implements NSCoding can be serialized for transports as Maps. Some classes are getting some special treatment for convinience on both sides.</p>
<pre>NSArray      - Maps to Java array or java.util.List, tansfered as Hessian list.
NSDictionary - Maps to Java java.util.Map, or domain class, trabsfered as Hessian map.
NSData       - Maps to Java byte array, transfered as Hessian binary data.
NSDate       - Maps to Java long or java.util.Date, transfered as Hessian date.
NSString     - Maps to Java java.lang.String, transfered as Hessian string.
NSXMLNode    - Maps to Java org.w3c.dom.Node, transfered as Hessian xml.</pre>
<p>That is it, now off to coding HessianKit 1.0 Final Candidate.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/07/10/hessiankit-released/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
	</channel>
</rss>

