<?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; Fredrik Olsson</title>
	<atom:link href="http://blog.jayway.com/author/fredrikolsson/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>Automated Testing is Like Optimizing</title>
		<link>http://blog.jayway.com/2011/01/07/automated-testing-is-like-optimizing/</link>
		<comments>http://blog.jayway.com/2011/01/07/automated-testing-is-like-optimizing/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 09:57:17 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6982</guid>
		<description><![CDATA[I have my roots in the Atari demo scene, so I know the joys of optimizing the inner-loop of a software texture mapper down to the last assembly instruction. The bragging rights of knowing that not a single clock cycle is wasted. I am also grown up enough to know that this is not a [...]]]></description>
			<content:encoded><![CDATA[<p>I have my roots in the Atari demo scene, so I know the joys of optimizing the inner-loop of a software texture mapper down to the last assembly instruction. The bragging rights of knowing that not a single clock cycle is wasted. I am also grown up enough to know that this is not a skill many needs to practice. In fact going about in this way on a customers project would be fraudulent, even if I could dazzle them with how cool optimizing for branch predictions is.</p>
<p>I can understand the joys of making sure that every potential bug is removed, and the bragging rights of 100% automated test coverage as well. But I would argue that it is equally fraudulent to claim 100% automated test coverage to a client as a virtue. I am not arguing that automated tests should be abandoned, far from it. I am arguing that automated tests should be applied with the same care as optimizations. </p>
<h2>Premature Automated Testing is Bad</h2>
<p>We have all learned that premature optimizations are bad. Guessing what could fail is hard, the only safe route would be to write a check for everything! There is even a coding practice encouraging this, test driven development or TDD for short. Which should really be called ADD for assertion driven development. Since what is done is not testing, but checking by asserting conditions against a specification.</p>
<p>Take a moment and answer honestly; for any project with good automated test coverage what is the ratio between time spent writing the checks versus the time these checks have saved you? In my experience the more zealously automated test coverage is applied, the more time is spent maintaining the tests. For any project where automated tests have been written first, and code later, I have yet never experienced that the checks have saved more time than the time they cost to develop and maintain.</p>
<p>When optimizing it is hard to find the bottlenecks. Gut feeling is good many times, but often even your gut feeling is wrong and the performance bottle neck is somewhere you would never expect. It is the same with defects in code, your gut feeling is good for pin-pointing many defects, but often the cause is something you never expected. So instead of wasting time guessing what the problems may be down the road you should inspect and measure where the issues are. And when an issue is found then you write a check for it to ensure it does not break again.</p>
<h2>Change the Algorithm</h2>
<p>The best optimization is often not to optimize at all, but to change to a better algorithm. Writing a bubble sort algorithm in assembly will never yield a better result than a sloppy merge sort written in C anyway, so do not waste your time.</p>
<p>Same can be said about code quality. If you have many issues, and your code breaks often, adding automated tests will only be bandaid until it breaks the next time. Change the code into something more stable. If needed, write checks to ensure the new implementation conforms to the same public API when you refactor it. Take notice to write checks with as good coverage as needed when you are about to refactor your code not before.</p>
<p>If you architect your application with many small independent units, each with a clearly defined public API, then refactoring is not a big problem.</p>
<h2>Perceived Quality</h2>
<p>All green lights and a 100% automated test coverage looks good on a report. But it can never catch what is most important of all; is the application valuable to the user? In that regard the 100% automated test coverage is a false safety, it gives the illusion of quality. A dangerous illusion that can be used to blind managers, customers and other stakeholders from seeing the real issues with the application.</p>
<p>There is yet no testing framework made that is as efficient as a human being actually using the application. Not just people blindly following a test protocol, that is even worse. But stake holders using the application as intended. Not just short burst before committing code to source control, but also regularly on longer sessions. So that you get a feel for how the app is used, what works, or just what grinds your gears. Usability issues are also issues and should be dealt with.</p>
<p>Not every issue is created equal. With the limited time every project have fixing, or predicting, each and every one of them is never feasible. So do not waste time fixing the one in a million issue, or writing checks for the bread and butter code. But do make sure the application fails gracefully. Fail as gracefully as you can for the end-user, they are very forgiving if you fail with style and make sure no data is lost. But also fail gracefully for yourself, be generous with logging when you do fail. And remember to add an automated check so that the reason for the failure may never raise again, once you fixed it.</p>
<h2>Model View Controller</h2>
<p>All application logic can be divided into three categories. Model for the business logic of your product, View for the display and input to and from the user (or other application), and Controller that is the mediator between the two. Any application of any significant size will have smaller MVC patterns within their units as well. Well defined boundaries between what is a Model, View and Controller is not only good for re-usability, maintainability, and replacing parts. It is also great for testing. Have well defined and testable public APIs for the parts, and the private implementations tend to be simpler and of higher quality. Do not let the public API be defined by how something is implemented, let the implementation be defined by how you want to access it from the outside. </p>
<p>Writing unit tests for the Model of your application is seldom a waste of time. Often the Model is what you begin implementing, so using unit tests as the incubator until you have enough logic in place to implement the first draft of your application is only rational; code that is unused is seldom of any quality at all.</p>
<p>Writing unit tests for the View yield much less returns on investment. It is also highly probably that you will have to write these tests over and over again. I would go so far as call them harmful, too many automated tests on the Views may in fact discourage you from doing drastic but needed usability changes. And no automated test in the world can ever flag if a View is usable, looks good, and feels right to the end-user.</p>
<p>Writing unit tests for the Controller should be a waste of time, otherwise your Controller is doing too much. A Controller should only be the mediator between the View and Model, if it does more then it should be split up and the proper parts moved into Model and View layers. So writing unit tests for a good Controller is basically just verifying that your are using the APIs of the Model and Views correctly. </p>
<h2>Conclusions</h2>
<p>We have learned that premature optimization is bad, often counter productive or wastes our time for minimal gains. Let us all grow up and also learn that premature automated testing is equally bad. The time we have is to precious to waste on overzealous automated testing instead of adding real value to the product by applying tests where it makes real difference to the products quality.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/01/07/automated-testing-is-like-optimizing/feed/</wfw:commentRss>
		<slash:comments>5</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>Localizations from NIB files</title>
		<link>http://blog.jayway.com/2010/10/05/localizations-from-nib-files/</link>
		<comments>http://blog.jayway.com/2010/10/05/localizations-from-nib-files/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 14:47:44 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6374</guid>
		<description><![CDATA[Cocoa Touch have good support for localizations. Pretty much any file can be localized, including NIB-files with user interface layouts. Unfortunately a NIB-file is an atomic file. So if you later need to do changes, like adding a new button, you will have to add this button to each and every NIB-file of each locale [...]]]></description>
			<content:encoded><![CDATA[<p>Cocoa Touch have good support for localizations. Pretty much any file can be localized, including NIB-files with user interface layouts. Unfortunately a NIB-file is an atomic file. So if you later need to do changes, like adding a new button, you will have to add this button to each and every NIB-file of each locale you support.</p>
<p>In practice this means that most developers tend to do the localization of NIBs manually in <code>-[viewDidLoad]</code>.  When finalizing Tweet Note for a <a href="http://ordedev.org/2010">Øredev 2010</a> release I once again hit this problem. A frequent problem should be abstracted away!</p>
<p>Here Android has the upper hand over iOS development. In Android the text localizations are separate from the layout localizations. If the layout need changes, then only the text needs to be localized.</p>
<h3>Let's do the same for iOS</h3>
<p>All texts that are set in Interface Builder are part of the archiving, and therefor set before <code>-[awakeFromNib]</code> is called. And  <code>-[awakeFromNib]</code> is in turn called before the UI is ever displayed to the user. So we have a hook that is guaranteed to
<ol>
<li>Be called for every object in the NIB.</li>
<li>Be called before the UI is ever displayed to the user</li>
</ol>
<p>Let's use this to our advantage. Thankfully UIKit is convention over configuration, so there are very few property names that we need to hook into; <code>text</code>, <code>title</code> and <code>placeholder</code>, are all shared by labels, text fields, bar button items, etc.</p>
<p>If we set a title for a textfield in Interface Builder to <code>"@username"</code>, then we want to use the <code>"username"</code> key from the <code>Localizable.strings</code> file, just as if we manually called upon <code>NSlocalizableString(@"username", nil)</code>.</p>
<p>All we need to do in <code>-[awakeFromNib]</code> is to check if any of these properties exist on the current instance, if so check if the first character of said property is <code>'@'</code>, then we do a translation. There will be a slight overhead, but nothing comparable to the I/O access for reading the NIB from disk.</p>
<pre class="brush: objc">-(NSString*)localizedValue:(NSString*)value;
{
    if ([value hasPrefix:@"@"]) {
    	value = NSLocalizedString([value substringFromIndex:1], nil);
    } else if ([value hasPrefix:@"\\@"]) {
        value = [value substringFromIndex:1];
    }
    return value;
}

-(void)localizeValueForKey:(NSString*)key;
{
    NSString* oldValue = [self valueForKey:key];
    NSString* newValue = [self localizedValue:oldValue];
    if (oldValue != newValue) {
        [self setValue:newValue forKey:key];
    }
}

-(void)awakeFromNib;
{
    if ([self respondsToSelector:@selector(text)]) {
        [self localizeValueForKey:@"text"];
    } else if ([self respondsToSelector:@selector(title)]) {
        [self localizeValueForKey:@"title"];
    }
    if ([self respondsToSelector:@selector(placeholder)]) {
        [self localizeValueForKey:@"placeholder"];
    }
}</pre>
<p>As an added bonus, we also check if the property starts with <code>"\@"</code> in wich case we remove the backward slash, this could be useful if we ever needed a text to begin with the actual <code>'@'</code> character.</p>
<h3>But what about buttons?</h3>
<p>Turns out that one very common UI component, the <code>UIButton</code>, do not have a title property. Instead the button have <code>-[setTitle:forState:</code>], so that different titles can be used depending on if the button is in normal, selected, disabled, etc, state. The states are actually a bit-mask, where 0 is the normal state. If no title has been set for the more specific states, then the normal state title will be used.</p>
<p>Let's add support for localizing buttons as well. We do this by localizing the normal state first. This way states without an overriding title will be ignored:</p>
<pre class="brush: objc">-(void)localizeButton;
{
    UIButton* button = (id)self;
    for (int state = 0; state < 8; state++) {
        NSString* oldTitle = [button titleForState:state];
        if (oldTitle != nil) {
            NSString* newTitle = [self localizedValue:oldTitle];
            if (oldTitle != newTitle) {
                [button setTitle:newTitle forState:state];
            }
        }
    }
}

-(void)awakeFromNib;
{
    if ([self respondsToSelector:@selector(text)]) {
        [self localizeValueForKey:@"text"];
    } else if ([self respondsToSelector:@selector(title)]) {
        [self localizeValueForKey:@"title"];
    } else if ([self isKindOfClass:[UIButton class]]) {
    	[self localizeButton];
    }
    if ([self respondsToSelector:@selector(placeholder)]) {
        [self localizeValueForKey:@"placeholder"];
    }
}</pre>
<h3>Conclusions</h3>
<p>Works like a charm. Adding a linear layout container view to adjust for different sizes in different locales is the final sprinkle of fairy dust, but worthy of a post of its own.<br />
Full source code that can be dropped into any iOS project can be <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/10/NSObject+CWNibLocalizations.zip'>downloaded here</a>. Source code is under Apache 2 license.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/10/05/localizations-from-nib-files/feed/</wfw:commentRss>
		<slash:comments>5</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>UIWebView and JavaScript Woes</title>
		<link>http://blog.jayway.com/2010/06/28/uiwebview-and-javascript-woes/</link>
		<comments>http://blog.jayway.com/2010/06/28/uiwebview-and-javascript-woes/#comments</comments>
		<pubDate>Mon, 28 Jun 2010 07:45:57 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5791</guid>
		<description><![CDATA[JavaScript Core is unfortunately not a public framework on iOS, leaving us at the mercy of the UIWebView class if we want to execute JavaScript in our applications. I have used JavaScript a lot recently and want to share four gotchas that I have had. Functional code! Turns out that JavaScript is functional, not as [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript Core is unfortunately not a public framework on iOS, leaving us at the mercy of the <code>UIWebView</code> class if we want to execute JavaScript in our applications. I have used JavaScript a lot recently and want to share four gotchas that I have had.</p>
<h3>Functional code!</h3>
<p>Turns out that JavaScript is functional, not as in working but as in a functional programming language. So when calling <code>-[UIWebView stringByEvaluatingJavaScriptFromString:]</code> you do not pass in for example:</p>
<pre class="brush:javascript">return x * y;</pre>
<p>But instead:</p>
<pre class="brush:javascript">x * y</pre>
<p>Yes even without the trailing <code>;</code> character! The result returned from <code>-[UIWebView stringByEvaluatingJavaScriptFromString:]</code> will be the value of the last statement, if you add a trailing <code>;</code> then the last statement will be an empty statement and you will get an empty string as a result. Took quite some time before I figured that one out. </p>
<h3><code>UIWebView</code> must be on screen to execute script</h3>
<p>The UIWebView class will not render any content, nor execute JavaScript if it is not potentially on screen. So you must add the UIWebView to the view hierarchy even if you just have it around for executing some JavaScript in the background.</p>
<p>It is perfectly ok to let the web view be 0x0 pixels, or full transparency, but hidden does not seem to work either.</p>
<h3>All access must be on the main thread</h3>
<p>Not news since the documentation clearly says you should only work with UIKit classes on the main thread (with a few added thread safe additions in IOS 4). But this is a problem if you want to do background tasks with JavaScript, since you must call <code>-[UIWebView stringByEvaluatingJavaScriptFromString:]</code> from the main thread. Any long running JavaScript will block all user input and updates of the screen.</p>
<p>No fear though, you can make your JavaScript asynchronous. But then <code>-[UIWebView stringByEvaluatingJavaScriptFromString:]</code> will return before your script has finished and <code>UIWebView</code> do not have any obvious other way to communicate any results back to you. Obvious way that is. What you instead have to do to get asynchronious results back into the Objective-C world is by fake URL requests. Use a function like this to return results from the JavaScript world:</p>
<pre class="brush:javascript">var returnAsyncResult = function(result, context) {
    window.location = 'result://dummy.com/' + result + '/' + context;
}</pre>
<p>And then let the delegate for your UIWebView get the result as such:</p>
<pre class="brush:objc">-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
    NSString* urlString = [[request URL] absoluteString];
    if ([urlString hasPrefix:@"result:"]) {
        NSString* path = [[request URL] path];
        NSArray* pathComponents = [path pathComponents];
        NSString* result = [pathComponents objectAtIndex:1];
        NSString* context = nil;
        if ([pathComponents count] > 2) {
            context = [pathComponents objectAtIndex:2];
        }
        [delegate javaScriptEvaluator:self
                      didReturnString:result
                              context:context];
        return NO;
    } else {
        return YES;
    }
}</pre>
<h3>Only String results</h3>
<p>Turns out that <code>-[UIWebView stringByEvaluatingJavaScriptFromString:]</code> only returns strings as result. No problem for simple types such as said strings and numbers, but a big problem if you try to return a complex value such as an array:</p>
<pre class="brush:javascript">[1,2,3]</pre>
<p>This will not work, and will return a <code>NSString</code> of zero length. You must explicitly convert arrays to strings before returning them to the Objective-C world, easiest way would be something like this:</p>
<pre class="brush:javascript">'[' + [1,2,3] + ']'</pre>
<h3>Conclusion</h3>
<p><code>UIWebView</code> is a blunt tool. Please do use <a href="http://bugreport.apple.com">http://bugreport.apple.com</a> and file a request to make JavaScript Core a public framework. The more duplicates, the higher Apple will prioritize this issue on their todo list.</p>
<p>In the meantime UIWebView can be used to your bidding if treated with care.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/06/28/uiwebview-and-javascript-woes/feed/</wfw:commentRss>
		<slash:comments>3</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>iPad, the Future, and the Luxury of Starting Over</title>
		<link>http://blog.jayway.com/2010/01/28/ipad-the-future-and-the-luxury-of-starting-over/</link>
		<comments>http://blog.jayway.com/2010/01/28/ipad-the-future-and-the-luxury-of-starting-over/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 20:02:59 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[cocoa touch]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[innovation]]></category>
		<category><![CDATA[ipad]]></category>
		<category><![CDATA[iphone]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4550</guid>
		<description><![CDATA[A luxury that you seldom have in the world of software development is the luxury of starting over. I am not talking about throwing away everything and start from scratch. But just taking what you have, and all the experiences learned. Apply some major refactoring to make what works really shine, and without care of [...]]]></description>
			<content:encoded><![CDATA[<p>A luxury that you seldom have in the world of software development is the luxury of starting over. I am not talking about throwing away everything and start from scratch. But just taking what you have, and all the experiences learned. Apply some major refactoring to make what works really shine, and without care of dependent clients throw out everything that turned out to be irreparable.</p>
<p>The <a href="http://www.apple.com/ipad/">iPad</a> as presented by Apple on the <a href="http://www.apple.com/ipad/">special january 2010 event</a> is a showcase of how Apple has been given this luxury. Not just once but over and over again. Allowing for iterating, and improving with each restart.</p>
<h3>The origins</h3>
<p>The evolution of the software running the iPad can be traced back along with <a href="http://en.wikipedia.org/wiki/Steve_Jobs">Steve Jobs</a> himself. With the first <a href="http://en.wikipedia.org/wiki/Macintosh">Macintosh</a> from 1984 he was one of the many talented people behind ushering the graphical user interface into the world of normal people. </p>
<p>Not entirely by his own choice he founded <a href="http://en.wikipedia.org/wiki/NeXT">NeXT</a> in 1985, and got the luxury of starting over, equipped with the experience from the Macintosh project. The lessons learned resulted in the NeXT computers in 1989, a system way ahead of it's time, with <a href="http://en.wikipedia.org/wiki/NeXTSTEP">NextStep's</a> object oriented frameworks, before OOP had even caught on with the main stream. Remember this was before <a href="http://en.wikipedia.org/wiki/Windows_3.0">Windows 3.0</a>.</p>
<p>In late 1996 Apple bought NeXT and all their assets, including Steve Jobs as the CEO. Now the experience learned from developing the NeXT computers and the NextStep operating system could be used again. With the luxury of a reset once again, throwing out anything that did not work, and clean up the parts that worked well. The new operating system rising from the ashes would be named <a href="http://en.wikipedia.org/wiki/Mac_OS_X">Mac OS X</a>, and the application development frameworks be called <a href="http://developer.apple.com/cocoa/">Cocoa</a>.</p>
<h3>The tech as used today</h3>
<p>Cocoa is the primary application development framework for Mac OS X to this day. It is an umbrella framework, containing:</p>
<ul>
<li><a href="http://developer.apple.com/mac/library/navigation/index.html#section=Frameworks&topic=Foundation">Foundation</a> - For the non-visual low level components.</li>
<li><a href="http://developer.apple.com/mac/library/navigation/index.html#section=Frameworks&topic=Application%20Kit">AppKit</a> - For the components to create a desktop application with mouse and keyboard</li>
<li><a href="http://developer.apple.com/mac/library/navigation/index.html#section=Frameworks&topic=Core%20Data">Core Data</a> - For managing application data as a graph database.</li>
</ul>
<p>The application development framework for <a href="http://en.wikipedia.org/wiki/IPhone_OS">iPhone OS</a> is called <a href="http://developer.apple.com/iphone/library/navigation/index.html#section=Frameworks&topic=Cocoa%20Touch%20Layer">Cocoa Touch</a>. It is basically all the nice parts from Foundation, and since iPhone OS 3.0 also Core Data. But AppKit is missing, instead replaced by <a href="http://developer.apple.com/iphone/library/navigation/index.html#section=Frameworks&topic=UIKit">UIKit</a>. UIKit are the components needed to create a graphical user interface based on multitouch. Not a dumbed down version of AppKit, but a rewrite that is re-using the experience from AppKit. Refining what works well, removing what did not turn out so well, and adding what could not easily be added to AppKit.</p>
<p>Apple gave themselves the luxury of starting over yet again, not burdened by backward compaitibility. The new form factor of the iPhone can not inspire any realistic hopes for application compatibility with the Mac computers. </p>
<h3>Where can this lead?</h3>
<p>Mac OS X and the Cocoa frameworks where good from a tech standpoint, and for us nerds. But not ready for prime-time by the average user until at least version 10.2, or 10.3 if you are really honest. Many dismissed the first versions of Mac OS X, while others saw the potential. I see the same thing with iPad and iPhone OS, it will be dismissed for now, and others will see a great potential.</p>
<p>I think that the iPad is Apple's vision for the future of computing. Mice to be replaced by multi-touch. The keyword being <strong>multi</strong>-touch. A touch device is to a multi-touch device what a black and white TV is to a modern color HD TV. Sure they both display pictures, the basic idea is there, but the execution is on a different level. In 1984 with the first Macintosh a computer mouse was a novelty. Apple want to replace the secondary input of the mouse, with direct input and manipulation using your very fingers. Making the mouse computer mouse a parenthesis in the history of computing.</p>
<p><strong>The iPhone OS is the successor to Mac OS X.</strong></p>
<p>There I said it. There will never be a Mac OX X 11.0, and probably not a Mac OS X 10.8 either. That line of succession is over, the new blood line to reign is the offspring that is iPhone OS. A fresh start, a luxury in our industry, and also a necessity in order to take the great leaps to the future.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/28/ipad-the-future-and-the-luxury-of-starting-over/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Learn to Stop Worrying and Love the Singleton</title>
		<link>http://blog.jayway.com/2010/01/15/learn-to-stop-worrying-and-love-the-singleton/</link>
		<comments>http://blog.jayway.com/2010/01/15/learn-to-stop-worrying-and-love-the-singleton/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 13:00:10 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[spring ldap]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4273</guid>
		<description><![CDATA[Enterprise applications and mobile applications have quite different requirements. Starting an enterprise application is just something you do once before it continue running for months or years. On the other side of the spectrum most mobile applications seldom runs for more than minutes, run by a bored users standing in line or riding the bus. [...]]]></description>
			<content:encoded><![CDATA[<p>Enterprise applications and mobile applications have quite different requirements. Starting an enterprise application is just something you do once before it continue running for months or years. On the other side of the spectrum most mobile applications seldom runs for more than minutes, run by a bored users standing in line or riding the bus. This means that a mobile application must start in an instant, whereas starting and enterprise application may take as long as it takes. </p>
<p>Dependency injection and early validation is crucial for an enterprise application, and <a href="http://www.springsource.org/">Spring</a> is a boon in this regard. But do not fool yourself, Spring is good, but it is not a universal cure. Especially not in mobile space where startup times, low memory consumption, and avoiding interfaces are virtues.</p>
<p>The bottleneck in an enterprise application is most probably the database, spending a few extra milliseconds here and there seldom matters. On much less performant mobile device those clock cycles are not only time the user has to spend waiting, it will drain the battery. A simple thing as using an interface instead of an abstract superclass will perform at least twice as slow. Even passing an extra argument in the constructors a few nestings deep will have an impact.</p>
<h3>Lazy Singeltons by Choice</h3>
<p>Class loading in Java is lazy, the Java VM will not load classes until they are referenced. Odds are that the user will not trigger a full coverage of all classes in your app for a short time running mobile app. If the user just checks for incoming messages and quits, then every class involved in composing messages do not need to be loaded. Early dependency injection breaks this, as all classes will be referenced at startup. Most components will be initialized in vain, as they are never actually used.</p>
<p>So what we should do in mobile application is to work more like the Java VM, and less like Spring. If possible do not create a component until it is requested. The best way to do this is using a singleton pattern. Not a normal enforced singleton pattern, but rather a singleton by choice. Let the constructor be public, trust your users, and name the getter <code>getSharedFoo()</code>, not <code>getInstance()</code>. Let me show you using a example of an URL cache component:</p>
<pre class="brush:java">public class URLCache {
  private static URLCache sharedCache;

  public static URLCache getSharedURLCache() {
    synchronized (URLCache.class) {
      if (sharedCache == null) {
        sharedCache = new URLCache();
      }
    }
    return sharedCache;
  }

  public URLCache() {
    // More code...
  }
  // Allot more code here...

}</pre>
<p>Using this shared URL cache component from our imaginary HTTP provider would then be super easy, but not mandatory:</p>
<pre class="brush:java">public class HTTPProvider {

  public InputStream inputStreamForURL(String url) {
    URLCache cache = URLCache.getSharedURLCache();
    // Use the cache...
  }

}</pre>
<p>The big win here is that if the code path of this run of the application never tries to open an input stream then the URL cache never has to be created. Saving several hundred milliseconds of reading cache indexes, validation, etc.</p>
<h3>But What About Testing?</h3>
<p>Are not singletons bad for unit tests and mocking components? They used to be. These days we have <a href="http://www.powermock.org/">PowerMock</a>, you really should use it. Turns out that not even PowerMock is really required, if we just change our singleton pattern very slightly, and allows the outside to set the shared component as well:</p>
<pre class="brush:java">public class URLCache {
  private static URLCache sharedCache;

  public static void setSharedURLCache(URLCache cache) {
    synchronized (URLCache.class) {
      sharedCache = cache;
    }
  }

  public static URLCache getSharedURLCache() {
    synchronized (URLCache.class) {
      if (sharedCache == null) {
        sharedCache = new URLCache();
      }
    }
    return sharedCache;
  }

  // Allot more code here...

}</pre>
<p>This small addition allows us for setup up our own mock cache in the setup of our unit tests. With something as simple as this:</p>
<pre class="brush:java">public class SomeTest extends TestCase {

  public void setUp() {
    URLCache.setSharedURLCache(new NoOpURLCache());
  }

  public void testRemoteResource() {
    assertNotNull(HTTPProvider.getSharedHTTPProvider().inputStreamForURL(TEST_URL));
  }
}</pre>
<p>It also allows us for explicitly override a singleton if our application has special needs, perhaps a more aggressive cache on a low bandwidth mobile data connection, or special implementation on a buggy Java ME platform. But most importantly for the normal case it will not waste time creating the component until it is actually needed, vastly improving the user experience for your mobile users.</p>
<h3>Take Aways</h3>
<p>Do not fear singletons, it is a great way of lazy creations that will greatly improve startup times and memory consumption on mobile applications.</p>
<p>Avoid using interfaces, they are at least twice as slow as classes, and can not have static methods for acquiring the lazy created components.</p>
<p>Do not enforce the singleton pattern, always use singleton by choice. To allow for testing and easy implementation of special cases.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/15/learn-to-stop-worrying-and-love-the-singleton/feed/</wfw:commentRss>
		<slash:comments>4</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>iPhone OS and the Lowest Common Denominator</title>
		<link>http://blog.jayway.com/2009/03/18/iphone-os-and-the-lowest-common-denominator/</link>
		<comments>http://blog.jayway.com/2009/03/18/iphone-os-and-the-lowest-common-denominator/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 10:04:00 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[innovation]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[sdk]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1178</guid>
		<description><![CDATA[Nishant wrote a good piece on why Apple continue to outdo it's rivals, he used a variant of a quote by Canadian hockey player Wayne Gretzky to make his point: A good hockey player plays where the puck is. A great hockey player plays where the puck is going to be. This is true as [...]]]></description>
			<content:encoded><![CDATA[<p>Nishant wrote a good piece on <a href="http://news.worldofapple.com/archives/2009/03/17/wayne-gretzky-and-why-apple-continues-to-outdo-its-rivals/">why Apple continue to outdo it's rivals</a>, he used a variant of a quote by Canadian hockey player Wayne Gretzky to make his point:</p>
<blockquote><p>A good hockey player plays where the puck is. A great hockey player plays where the puck is going to be.</p></blockquote>
<p>This is true as it stands, but I think the main reason why Apple can keep a pace and a high standard of inovation is because of how they manage the Lowest Common Denominator. And iPhone OS with App Store is the crown jewel.</p>
<h3>Technology vs. User Base</h3>
<p>The lowest common denominator is always of interest when developing applications and services for the end user with profit interests. The lowest common denominator is what defines your user base, and it is a hard game of balance. Sticking to the newest technology will allow you to progress faster with more elegant solutions, whereas using a more commonly available technology will give you a larger user base.</p>
<p>So the lowest common denominator should be as high as possible, while still economical. With Java ME a bold effort to rise the bar of the lowest common denominator is the <a href="http://jcp.org/en/jsr/detail?id=248">MSA JSR-248</a>. An effort to give Java ME developers a guarantee minimum of features. A noble effort, but in reality up to a year ago only Sony Ericsson was MSA compliant, making the aged MIDP 2.0 the de-facto lowest common denominator for any developer targeting a the majority of Java ME devices.</p>
<p>The lowest common denominator for an average Java ME developer is the MIDP 2.0 spec from 2002.</p>
<h3>iTunes as a Hub</h3>
<p>Apple has a different situation, largely due to it's decision to use iTunes as the hub for all mobile devices, iPods as well as iPhones. All iPods and iPhones charges the battery by plugging in the USB-cable to your computer, this have some large but not obvious benefits.</p>
<p>Most notably Apple knows with 100% certainty that all users will have their devices on a reliable and controlled connection often, in most cases on a daily basis. As the users also use iTunes to synchronize their media, any other synchronization is not a hassle but rather a bonus on top of something they already requested.</p>
<p>Adding software updates on top of synchronizing media and data content through iTunes is just genius. It is a two click operation for the user, and as a result Apple virtually guaranteed that all iPod and iPhone users have <a href="http://www.theiphoneblog.com/2009/03/14/iphone-firmware-running/">the very latest software installed</a> on their device.</p>
<h3>Back-porting Software</h3>
<p>Apart from the technology decision with iTunes as a hub, Apple have also made a business decision by always back porting their latest software to all iPhone OS powered devices. iPhone OS 2.0 can be installed on any first generation iPod Touch or iPhone, and with iPhone OS 3.0 this summer all three generations will be supported.</p>
<p>This back-porting model is the total oposite of almost all competitors, where instead new features are explicitly locked to the latest hardware in order to sell devices. So if the end users can get all the new iPhone 3.0 as a free download, why should they buy new hardware? Will not Apple loose revenue on unsold third generation iPhone devices? </p>
<p>In short term probably will, but the big win is <strong>the Lowest Common Denominator</strong>. Whereas the competition have a common lowest denominator of several years, almost a decade, Apple and all of Apple's third party developers have a lowest common denominator of virtually weeks.</p>
<h3>Conclusion</h3>
<p>With a simple software distribution model that guarantees the lowest common denominator Apple has guaranteed that the common lowest denominator is the current software, period. This allows Apple, and all third party developer creating applications and services for their devices, the luxury of discarding all effort for backward compatibility, and technological compromises.</p>
<p>Apple and we are allowed to innovate with full steam ahead.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/18/iphone-os-and-the-lowest-common-denominator/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Hidden methods in Sony Ericsson Java Platform</title>
		<link>http://blog.jayway.com/2009/03/09/hidden-methods-in-sony-ericsson-java-platform/</link>
		<comments>http://blog.jayway.com/2009/03/09/hidden-methods-in-sony-ericsson-java-platform/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 07:58:00 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1069</guid>
		<description><![CDATA[It is no secret that the published interfaces for MIDP classes in any JavaME Platform is only a subset of what in reality is there. Most of the native calls needed to interact with the underlying native platform, and other helper methods, are hidden from us. Mostly for good, and sometimes for bad... The Anecdotal [...]]]></description>
			<content:encoded><![CDATA[<p>It is no secret that the published interfaces for MIDP classes in any JavaME Platform is only a subset of what in reality is there. Most of the native calls needed to interact with the underlying native platform, and other helper methods, are hidden from us. Mostly for good, and sometimes for bad...</p>
<h3>The Anecdotal History</h3>
<p>We are developing a custom application framework on top of MIDP, adding a MVC application model, and modern interface components with touch and animation support. All this is build on top of a shared subclass of <code>Canvas</code>, and our own custom drawing with screen transitions, etc. is implemented on top of that.</p>
<p>An interface component is called a <code>View</code>, and any interface component that can host other interface components implements the <code>ViewParent</code> interface. Simple until I introduces the method <code>hasFocus()</code>. All of a sudden the application refused to run on target Sony Ericsson device. The emulator worked nice, our P1i worked, even the Xperia X1 run. But none of the cybershots, or walkmans with JP-7 or JP-8.</p>
<p><em>"Application error</em>". Oh well, that means that something threw an exception during the MIDlet constructor or <code>appStart()</code> call. So add pedantic catches, and display the error in an <code>Alert</code>; <em>"NoClassDefFoundError"</em>.</p>
<h3>The Problem</h3>
<p><code>NoClassDefFoundError</code> on the OSE phones, but no other installed with the same jad/jar-files, that is strange. Unfortunately Sony Ericsson has a policy of removing all error messages from exceptions, so no clue as to what class is missing either. Turn off Proguard optimization, still does not work, still <code>NoClassDefFoundError</code>. Head back to the Subversion logs and binary search, what is the latest revision that worked? And what was changed?</p>
<p>Turnes out that the shared <code>Canvas</code> subclass that implement the aforementioned interface <code>ViewParent</code> got the new method <code>hasFocus()</code>, and that is the only change from the working revision, to the broken revision.</p>
<p><em>- "I'm pretty sure that is working."</em>, one of the half dozen bug-hunting team member said looking at:
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> hasFocus<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;">return</span> <span style="color: #000000; font-weight: bold;">true</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>As it turns out the platform implementation of the MIDP class <code>Canvas</code> has a hidden method named <code>hasFocus()</code>. It is not <code>private</code>, but declared as <code>public</code> and <code>final</code>, but not exposed in the public API. So when our subclass is loaded, our <code>public hasFocus()</code> method clashes with the unexposed <code>public final hasFocus()</code> of the platform's implementation.</p>
<h3>Solution, and Lesson Learned</h3>
<p>The method <code>hasFocus()</code> was renamed to <code>isInFocus()</code>, and now everything works again.</p>
<p>From now on we will:</p>
<ul>
<li>Never trust subclasses of MIDP classes.</li>
<li>Test on device early and often, also for obvious changes.</li>
<li>Always keep commits small and atomic.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/09/hidden-methods-in-sony-ericsson-java-platform/feed/</wfw:commentRss>
		<slash:comments>0</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>Fixing Image#getRGB()</title>
		<link>http://blog.jayway.com/2009/01/17/fixing-imagegetrgb/</link>
		<comments>http://blog.jayway.com/2009/01/17/fixing-imagegetrgb/#comments</comments>
		<pubDate>Sat, 17 Jan 2009 11:47:25 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[midp]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=813</guid>
		<description><![CDATA[I have encountered a problem when implementing a nine-patch painter for MIDP 2.0, most of my graphics where left transparent for no-reason. A nine-patch is an image with a flexible center row, and a flexible center column. Most useful when doing themed UI, as a single image can be used to draw buttons, and boxes [...]]]></description>
			<content:encoded><![CDATA[<p>I have encountered a problem when implementing a nine-patch painter for MIDP 2.0, most of my graphics where left transparent for no-reason. A nine-patch is an image with a flexible center row, and a flexible center column. Most useful when doing themed UI, as a single image can be used to draw buttons, and boxes of any sizes. </p>
<p>The four corners are coped as is, the four borders scaled in a single direction, and the center is scaled in both directions. Since MIDP do not support image scaling this must be implemented by hand using the ARGB values fetched using <code>Image#getRGB()</code>. The documentation is quite straight forward, but fail to mention one pecularity in many implementation...</p>
<h3>Clearing unwanted data</h3>
<p>I want to create the target image in a single <code>int[]</code> array to reduce memory usage. No problem copying image data into this structure, it is just what the quite straightforward API is designed to do:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> getRGB<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> rgbData,
                   <span style="color: #993333;">int</span> offset, <span style="color: #993333;">int</span> scanlength,
                   <span style="color: #993333;">int</span> x, <span style="color: #993333;">int</span> y,
                   <span style="color: #993333;">int</span> width, <span style="color: #993333;">int</span> height<span style="color: #66cc66;">&#41;</span></pre>
<p>Unfortunately the documentation fails to mention that many implementations will not as expected just ignore data in <code>rgbData</code> that is not copied. Instead zeroes, or transparent pixels, will be filled in for any image data that has not been requested on a per row basis. I dare anyone to find where this is mentioned in the <a href="http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html">MIDP spec</a>.</p>
<h3>A solution</h3>
<p>The solution is to write your own wrapper method for <code>Image#getRGB()</code> that copies just a single row of image data at a time, and the requested scanline length must be lied about to avoid having the remainder of lines filled with zeroes. Here is tho code ready for copy and paste:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ImageUtils <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> getRGBFromImage<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AImage+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Image</span></a> image, <span style="color: #993333;">int</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> argbData, <span style="color: #993333;">int</span> offset,
            <span style="color: #993333;">int</span> scanline, <span style="color: #993333;">int</span> x, <span style="color: #993333;">int</span> y, <span style="color: #993333;">int</span> width, <span style="color: #993333;">int</span> height<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> row = <span style="color: #cc66cc;">0</span>; row &lt; height; row++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            image.<span style="color: #006600;">getRGB</span><span style="color: #66cc66;">&#40;</span>argbData, offset, width, x, y + row, width, <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
            offset += scanline;
        <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/01/17/fixing-imagegetrgb/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

