<?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; mobile</title>
	<atom:link href="http://blog.jayway.com/tag/mobile/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +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>Android: The Mysterious NullPointerException</title>
		<link>http://blog.jayway.com/2011/12/15/android-the-mysterious-nullpointerexception/</link>
		<comments>http://blog.jayway.com/2011/12/15/android-the-mysterious-nullpointerexception/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 15:27:19 +0000</pubDate>
		<dc:creator>Darius Katz</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11594</guid>
		<description><![CDATA[The Problem One day it was just there. A mischievous NullPointerException causing, eh, mischief. It was fairly easy to provoke with my application but for some reason my code was not part of the stacktrace. 12-07 14:42:52.722 E/AndroidRuntime(18421): FATAL EXCEPTION: main 12-07 14:42:52.722 E/AndroidRuntime(18421): java.lang.NullPointerException 12-07 14:42:52.722 E/AndroidRuntime(18421): at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1064) 12-07 14:42:52.722 E/AndroidRuntime(18421): at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1081) [...]]]></description>
			<content:encoded><![CDATA[<p><strong>The Problem</strong><br />
One day it was just there. A mischievous <em>NullPointerException</em> causing, eh, mischief. It was fairly easy to provoke with my application but for some reason my code was not part of the stacktrace.</p>
<pre>
12-07 14:42:52.722 E/AndroidRuntime(18421): FATAL EXCEPTION: main
12-07 14:42:52.722 E/AndroidRuntime(18421): java.lang.NullPointerException
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1064)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1081)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at android.os.Handler.handleCallback(Handler.java:587)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at android.os.Handler.dispatchMessage(Handler.java:92)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at android.os.Looper.loop(Looper.java:130)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at android.app.ActivityThread.main(ActivityThread.java:3701)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at java.lang.reflect.Method.invokeNative(Native Method)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at java.lang.reflect.Method.invoke(Method.java:507)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
12-07 14:42:52.722 E/AndroidRuntime(18421): 	at dalvik.system.NativeStart.main(Native Method)
</pre>
<p>I fretted. I winced. I even felt a slight irritation coming on.</p>
<p><strong>The Solution</strong><br />
In the end I found out the reason behind the mysterious <em>NullPointerException</em>. My application is binding to a Service and it turns out that the <em>ContextWrapper.bindService()</em>-method can't take a <em>null</em> as its <em>ServiceConnection</em> parameter. </p>
<p><em>ContextWrapper.bindService():</em><br />
<a href="http://developer.android.com/reference/android/content/ContextWrapper.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">public boolean bindService (Intent service, ServiceConnection conn, int flags)</a><br />
<code>Connect to an application service, creating it if needed.</code></p>
<p>Instead of throwing a helpful <em>IllegalArgumentException</em> it forwards the erroneous <em>null</em>-parameter into the innards of The Android Service Beast. That part is then unable to use it and throws a <em>NullPointerException</em> instead together with its own stacktrace which your code is not a part of.</p>
<p><strong>The Summary</strong><br />
In short, make sure you don't pass <em>bindService()</em> a <em>null</em> as the <em>ServiceConnection</em> parameter or you will get an unknown <em>NullPointerException</em> which is hard to track down.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/15/android-the-mysterious-nullpointerexception/feed/</wfw:commentRss>
		<slash:comments>0</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>Design/performance &#8211; WP7 in blend and code</title>
		<link>http://blog.jayway.com/2011/03/31/designperformance-wp7-in-blend-and-code/</link>
		<comments>http://blog.jayway.com/2011/03/31/designperformance-wp7-in-blend-and-code/#comments</comments>
		<pubDate>Thu, 31 Mar 2011 08:47:32 +0000</pubDate>
		<dc:creator>Håkan Reis</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[User Experience]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[techdays]]></category>
		<category><![CDATA[user experience]]></category>
		<category><![CDATA[ux]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=7809</guid>
		<description><![CDATA[We (Andreas Hammar and I) are just returning from Tech-Days 2011, we delivered a session on developing applications for Windows Phone 7 in Blend and code. While we were preparing for this session something stuck in our minds - when it comes to mobile applications the top priority is in design and performance. Design and [...]]]></description>
			<content:encoded><![CDATA[<p>We (<a href="http://blog.jayway.com/author/andreashammar/" target="_blank">Andreas Hammar</a> and <a href="http://blog.jayway.com/author/hakanreis/" target="_blank">I</a>) are just returning from Tech-Days 2011, we delivered a session on developing applications for Windows Phone 7 in Blend and code. While we were preparing for this session something stuck in our minds - when it comes to mobile applications the top priority is in design and performance.</p>
<blockquote><p><strong>Design and performance</strong> over architecture and frameworks</p></blockquote>
<p>We have to focus our attention on the user experience, how the application is perceived and not what technology is used or how the application is built. The important thing is that the application is well designed and that it responds to the user. SO to be a WP7 developer there are two things you really have to study, and study hard:</p>
<blockquote><p><strong>Design<br />
Performance</strong></p></blockquote>
<p>We're not suggesting that you throw out all the knowledge around architecture and framework. But, if it impacts design and performance you should think twice about why. Also, as Johan Lindfors said in his session – “<strong>stop building frameworks! </strong>Start building applications”</p>
<h2>Slides and samples</h2>
<p>Anyway, to sum this up we share the slides on slideshare as well as provide the code and slides as files below.</p>
<div id="__ss_7458800" style="width: 425px;"><strong style="display: block; margin: 12px 0 4px;"><a title="Windows Phone 7 in Blend and Code" href="http://www.slideshare.net/haqwin/windows-phone-7-in-blend-and-code">Windows Phone 7 in Blend and Code</a></strong><object id="__sse7458800" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=windowsphone7inblendandcode-110331033737-phpapp01&amp;stripped_title=windows-phone-7-in-blend-and-code&amp;userName=haqwin" /><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><embed type="application/x-shockwave-flash" width="425" height="355" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=windowsphone7inblendandcode-110331033737-phpapp01&amp;stripped_title=windows-phone-7-in-blend-and-code&amp;userName=haqwin" name="__sse7458800" allowscriptaccess="always" allowfullscreen="true"></embed></object></div>
<p>&nbsp;</p>
<blockquote><p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/demo.zip" target="_self">Windows Phone 7 in blend and code – code</a><br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/WindowsPhone7InBlendAndCode.pdf" target="_self">Windows Phone 7 in blend and code - slides</a></p></blockquote>
<h2>Resources</h2>
<p>Following is a collection of useful links to get started with real development - just promise you don’t build another framework.</p>
<ul>
<li><a href="http://windowsteamblog.com/windows_phone/b/wpdev/archive/2010/03/18/windows-phone-7-series-ui-design-amp-interaction-guide.aspx" target="_blank">The UI and interaction guideline for Windows Phone 7</a></li>
<li><a href="http://www.jeff.wilcox.name/2011/03/metro-design-guide-v1/" target="_blank">Jeff Wilcox designer guideline for developers</a></li>
<li><a href="http://blogs.msdn.com/b/ptorr/archive/2010/10/30/that-memory-thing-i-promised-you.aspx" target="_blank">Peter Torr’s memory profiler</a></li>
<li><a href="http://silverlight.codeplex.com/" target="_blank">Silverlight Toolkit</a></li>
<li><a href="http://blogs.msdn.com/b/delay/archive/2010/09/02/keep-a-low-profile-lowprofileimageloader-helps-the-windows-phone-7-ui-thread-stay-responsive-by-loading-images-in-the-background.aspx" target="_blank">LowProfileImageLoader</a> by David Anson</li>
<li><a href="http://www.scottlogic.co.uk/blog/colin/2011/01/windows-phone-7-deferredloadcontentcontrol/" target="_blank">DeferredLoadContentControl</a> by Colin Eberhardt</li>
<li>Peter Torr’s <a href="http://blogs.msdn.com/b/ptorr/archive/2010/10/12/procrastination-ftw-lazylistbox-should-improve-your-scrolling-performance-and-responsiveness.aspx" target="_blank">LazyListBox</a></li>
<li>Gif decoder as part of the <a href="http://imagetools.codeplex.com/" target="_blank">ImageTools for silverlight</a></li>
</ul>
<p>Be creative! // <a href="http://blog.jayway.com/author/andreashammar/" target="_blank">Andreas Hammar</a> &amp; <a title="about me" href="http://blog.jayway.com/author/hakanreis/" target="_blank">Håkan Reis</a></p>
<p><script src="http://b.scorecardresearch.com/beacon.js?c1=7&amp;c2=7400849&amp;c3=1&amp;c4=&amp;c5=&amp;c6="></script> <script src="http://b.scorecardresearch.com/beacon.js?c1=7&amp;c2=7400849&amp;c3=1&amp;c4=&amp;c5=&amp;c6="></script></p>
<p><script src="http://b.scorecardresearch.com/beacon.js?c1=7&amp;c2=7400849&amp;c3=1&amp;c4=&amp;c5=&amp;c6="></script><script src="http://b.scorecardresearch.com/beacon.js?c1=7&amp;c2=7400849&amp;c3=1&amp;c4=&amp;c5=&amp;c6="></script></p>
<p><script src="http://b.scorecardresearch.com/beacon.js?c1=7&amp;c2=7400849&amp;c3=1&amp;c4=&amp;c5=&amp;c6="></script><br />
<script src="http://b.scorecardresearch.com/beacon.js?c1=7&amp;c2=7400849&amp;c3=1&amp;c4=&amp;c5=&amp;c6="></script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/03/31/designperformance-wp7-in-blend-and-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cucumber tests on iPhone/iPad</title>
		<link>http://blog.jayway.com/2011/02/11/cucumber-tests-on-iphoneipad/</link>
		<comments>http://blog.jayway.com/2011/02/11/cucumber-tests-on-iphoneipad/#comments</comments>
		<pubDate>Fri, 11 Feb 2011 10:18:18 +0000</pubDate>
		<dc:creator>Davor Crnomat</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[Cucumber]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=7129</guid>
		<description><![CDATA[I am sure everybody has heard about Cucumber ( https://github.com/aslakhellesoy/cucumber) – a tool for Behaviour Driver Development where you describe software behavior in natural language that your customer can understand. Through step definitions these behavior descriptions are executed as automated tests. Cucumber serves as documentation, automated tests and development aid. My friend and colleague Christian [...]]]></description>
			<content:encoded><![CDATA[<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">I am sure everybody has heard about Cucumber ( </span></span></span><span style="color: #000071;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><span style="text-decoration: underline;">https://github.com/aslakhellesoy/cucumber</span></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">) – a tool for Behaviour Driver Development where you describe software behavior in natural language that your customer can understand. Through step definitions these behavior descriptions are executed as automated tests. Cucumber serves as documentation, automated tests and development aid.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">My friend and colleague Christian Hedin gave me tips on iCuke. Cucumber has been widely used for testing web applications, but now it’s also possible to test iOS (iPhone and iPad) apps with help of the iCuke library (</span></span></span><span style="color: #000071;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><span style="text-decoration: underline;">https://github.com/unboxed/icuke</span></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">). iCuke uses AppleScript to drive XCode in order to launch your application into the iOS Simulator. A preloaded library is used to inject a small HTTP server into your application. The HTTP server allows you to see an XML representation of the iOS device screen and to emulate input, such as taps, swipes and pinch gestures.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">You can read more about it here:<br />
</span></span></span><span style="font-family: 'Times New Roman', serif; font-size: small; color: #000071;"><span style="text-decoration: underline;">http://www.unboxedconsulting.com/blog/cucumber-iphone-icuke<br />
</span></span><span style="font-family: 'Times New Roman', serif; font-size: small; color: #000071;"><span style="text-decoration: underline;">http://pragprog.com/magazines/2010-07/bdd-on-iphone-icuke</span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Really excited about Cucumber on iPhone we decided to give it a try. After installing iCuke and doing some test runs it was clear that some challenges had to be overcome to make this a truly useful tool for Behaviour Driven Development and automated testing of iOS apps.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Challenge 1: Screen returns the previous screen's xml</strong></span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">In our test, we wanted to tap a button, come to another screen and expected to see a text. When the test runs the iPhone is driven to the correct screen, e can see the expected text but the test fails anyway. After little debugging we realized that the method </span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><em>screen.xml</em></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"> returns old xml directly after changing the screen.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Solution: </strong></span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">We needed to refresh screen before checking if the expected text is on the new screen. iCuke has a method to refresh screen but it is private and we could not use it. So we just added a new method to the existing ICukeWorld class.</span></span></span></p>
<pre class="code"><span style="color: #500000;"><span style="font-size: x-small;"><strong>class</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> ICukeWorld</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>def</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> refresh_screen</span></span>
<span style="color: #000000;">   <span style="font-size: x-small;">refresh</span></span>
<span style="color: #000000;">   <span style="font-size: x-small;">screen</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Calling this method before checking for the presence of the text solved this problem. </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Later on, I forked iCuke and added this and some other methods.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Courier New';"><span style="font-size: small;">git://github.com/DavorC/icuke.git</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Challenge 2: Timing</strong></span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Everybody knows that using sleep and delays in code is not so flexible.</span></span></span></p>
<pre class="ruby"><span style="color: #210000;"><span style="font-size: x-small;">sleep</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">3</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #444444;"><span style="font-size: x-small;"># wait 3 seconds</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">We want to check something on the screen and give it 3 seconds to finish its loading. </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Is it enough? Maybe, maybe not. Screen content loading could take 0.1 second or 5 seconds or... - You know what I mean. </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">In the first case loading is finished quickly and we unnecessarily spend 3 seconds for doing nothing . If we have a lot of delays in our code then our tests would waste a lot of precious time. </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">In the second case the delay is not long enough and the test fails.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Solution:</strong></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"> </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">We need to write some help functions to wait for different items which are expected: some text, a button, downloading spinner etc.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Example with wait for text:</span></span></span></p>
<pre class="ruby"><span style="color: #500000;"><span style="font-size: x-small;"><strong>def</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> wait_for_text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">text, timeout </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@timeout</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> </span><span style="color: #210000;"><span style="font-size: x-small;">puts</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"#{method_name}(#{text}, #{timeout})"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>if</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@debug</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">refresh_screen</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">start_time </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> Time</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">now</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>until</strong></span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">screen</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">exists?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">))</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>   if</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> Time</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">now </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">-</span></span><span style="color: #000000;"><span style="font-size: x-small;"> start_time &gt; timeout</span></span>
<span style="color: #000000;">     <span style="font-size: x-small;">flunk</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"#{method_name}: Timed out after #{timeout} seconds"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;">   </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>
<span style="color: #000000;">   </span><span style="color: #210000;"><span style="font-size: x-small;">sleep</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #215f00;"><span style="font-size: x-small;">0.1</span></span>
<span style="color: #000000;">   <span style="font-size: x-small;">refresh_screen</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">As you can see the method is waiting for the text to appear and does checking every 0.1 second. As soon as the text is found the test continues. If, after given timeout, the text is still not found, the test fails.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">I prefer to use unit test assertions in my tests (</span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><em>flunk</em></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"> is an assert which always fails). To use assertions with cucumber you need to add assertions to the Cucumber World:</span></span></span></p>
<pre class="ruby"><span style="color: #210000;"><span style="font-size: x-small;">require</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">'test/unit/assertions'</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">World</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">Test::Unit::Assertions</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Challenge 3: </strong></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"> </span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Different tappable object on screen can have the same text label.</strong></span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Identifying objects on the screen only by text is not enough.</span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong> </strong></span></span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">By default, the first tappable object is tapped. What if we want to tap the second one?</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;"><strong>Solution:</strong></span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">I created a set of help functions for: </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">returning all objects that satisfy some criteria</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">returning a specific object</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">waiting for a specific object</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">checking if a specific object exists</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Objects are described in xml by: type, label, traits and index.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Here is an example of getting an array of all elements satisfying given attribute values.</span></span></span></p>
<pre class="ruby"><span style="color: #500000;"><span style="font-size: x-small;"><strong>def</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> get_all_elements_by_type_label_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> </span><span style="color: #210000;"><span style="font-size: x-small;">puts</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"#{method_name}(#{type}, #{label}, #{traits})"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>if</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@debug</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">refresh_screen</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">doc </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> REXML::Document</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>new</strong></span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">screen</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">xml</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">to_s</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">elements </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> REXML::XPath</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">match</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">doc, </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"//#{type}[@label=#{label.inspect}][@traits=#{traits.inspect}]"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">elements</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Observe how it is easy to parse xml using ruby's REXML library.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Of course I could write more generic methods and decrease number of code lines - something like: </span></span></span></p>
<pre class="ruby"><span style="color: #000000;"><span style="font-size: x-small;">get_all_elements</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, options </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #4f005f;"><span style="font-size: x-small;">{}</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">but I like readability so I wrote a set of help functions with more specific naming:</span></span></span></p>
<p><span style="color: #000000;"><span style="font-size: x-small;">get_element_by_type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)<br />
</span></span><span style="font-size: 13.2px;"><span style="color: #000000;"><span style="font-size: x-small;">get_element_by_type_and_label</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)<br />
</span></span></span><span style="font-size: 13.2px;"><span style="color: #000000;"><span style="font-size: x-small;">get_element_by_type_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, traits, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_element_by_type_label_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, traits, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_elements_by_type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_elements_by_type_and_label</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_elements_by_type_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_elements_by_type_label_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_static_texts</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">()</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_labels_by_type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_all_labels_by_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">element_by_type_exists?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">element_by_type_and_label_exists?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">element_by_type_and_traits_exists?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, traits, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">element_by_type_label_and_traits_exists?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, traits, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">text_exists?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">wait_for_element_by_type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #000000;"><span style="font-size: x-small;">, timeout </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@timeout</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">wait_for_element_by_type_and_label</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #000000;"><span style="font-size: x-small;">, timeout </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@timeout</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">wait_for_element_by_type_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, traits, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #000000;"><span style="font-size: x-small;">, timeout </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@timeout</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">wait_for_element_by_type_label_and_traits</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">type, label, traits, index </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #000000;"><span style="font-size: x-small;">, timeout </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@timeout</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">wait_for_text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">text, timeout </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> @@timeout</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">get_center_of_the_element</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">element</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">tap_coordinates</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">x, y</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">double_tap_coordinates</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">x, y</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">tap_element</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">element</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">double_tap_element</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">element</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">tap_text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><br />
<span style="color: #000000;"><span style="font-size: x-small;">double_tap_text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">In order to use these functions you need to use iCuke from:</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Courier New';"><span style="font-size: small;">git://github.com/DavorC/icuke.git</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Don't forget to use –recursive flag when you clone it:</span></span></span></p>
<pre><span style="color: #000000;"><span style="font-family: 'Courier New';"><span style="font-size: small;">git clone --recursive git://github.com/DavorC/icuke.git</span></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">After building and installing the iCuke gem you need to </span></span></span></p>
<pre><span style="color: #210000;"><span style="font-size: x-small;">require</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">'icuke/cucumber_ext'</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">instead of:</span></span></span></p>
<pre><span style="color: #210000;"><span style="font-size: x-small;">require</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">'icuke/cucumber'</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: Arial, sans-serif;"><span style="font-size: medium;">Example of usage</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">In your feature-file:</span></span></span></p>
<pre><span style="color: #000000;"><span style="font-size: x-small;">Background:</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">Given </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"myApp.xcodeproj"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> is loaded </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>in</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> the simulator</span></span>

<span style="color: #000000;"><span style="font-size: x-small;">Scenario Outline: User try to login with different invalid credentials with valid signs</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">When I am in </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Account"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> section</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;"> And I paste in username </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"&lt;user&gt;"</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;"> And I paste in password </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"&lt;pass&gt;"</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;"> And I tap Login button</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">Then I will see alert dialog</span></span>

<span style="color: #000000;"> <span style="font-size: x-small;">Examples:</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">| user            | pass      |</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">| </span></span><span style="color: #210000;"><span style="font-size: x-small;">test</span></span><span style="color: #000000;"><span style="font-size: x-small;">@</span></span><span style="color: #210000;"><span style="font-size: x-small;">test</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">com   | </span></span><span style="color: #210000;"><span style="font-size: x-small;">test</span></span><span style="color: #000000;"><span style="font-size: x-small;">      |</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">| 123456          | qwertyui  |</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">| </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">..</span></span><span style="color: #000000;"><span style="font-size: x-small;">@</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">..</span></span><span style="color: #000000;"><span style="font-size: x-small;">com        | </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;"> €&lt;&gt; |</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">step definitions:</span></span></span></p>
<pre class="ruby"><span style="color: #000000;"><span style="font-size: x-small;">When </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">/</span></span><span style="color: #000000;"><span style="font-size: x-small;">I am </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>in</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"(.*)"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> section</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">/</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> |section|</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">wait_for_text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">section</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">tap</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">section</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-family: Courier, 'Courier New', monospace;"><span style="font-size: x-small;">wait_for_element_by_type_and_label</span></span></span><span style="color: #6d6e1d;"><span style="font-family: Courier, 'Courier New', monospace;"><span style="font-size: x-small;">(</span></span></span><span style="color: #0400e6;"><span style="font-family: Courier, 'Courier New', monospace;"><span style="font-size: x-small;">"UINavigationItemView"</span></span></span><span style="color: #000000;"><span style="font-family: Courier, 'Courier New', monospace;"><span style="font-size: x-small;">, section</span></span></span><span style="color: #6d6e1d;"><span style="font-family: Courier, 'Courier New', monospace;"><span style="font-size: x-small;">)</span></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>

<span style="color: #000000;"><span style="font-size: x-small;">When </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">/</span></span><span style="color: #000000;"><span style="font-size: x-small;">I paste </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>in</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> username </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"(.*)"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">/</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> |user|</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">label </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"E-mail"</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">refresh_screen</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">assert</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">get_all_static_texts</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">().</span></span><span style="color: #000000;"><span style="font-size: x-small;">include?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">label</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><span style="color: #000000;"><span style="font-size: x-small;">, </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"No text field with label #{label} was found"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">write_to_mac_clipboard</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">user</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">paste_clipboard_to_text_field</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"UITextFieldLabel"</span></span><span style="color: #000000;"><span style="font-size: x-small;">, label</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>

<span style="color: #000000;"><span style="font-size: x-small;">When </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"I tap Login button"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">wait_for_text</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Login"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">tap</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Login"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #5a5c00;"> </span><span style="color: #000000;"><span style="font-size: x-small;">wait_for_download_indicator_finish</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>

<span style="color: #000000;"><span style="font-size: x-small;">Then </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"I will see alert dialog"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">wait_for_element_by_type</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"UIAlertView"</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: Arial, sans-serif;"><span style="font-size: medium;">Testing both iPhone and iPad</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">If you’re testing a universal app that runs on both iPhone and iPad I recommend writing different scenarios for the platforms. iPad in landscape mode is most likely to reuse most of code you have written for iPhone. Place them in different feature files and tag them with e.g. @iphone respective @ipad tags.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">In your env.rb file:</span></span></span></p>
<pre class="ruby"><span style="color: #000000;"><span style="font-size: x-small;">$PLATFORM </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"iphone"</span></span>

<span style="color: #000000;"><span style="font-size: x-small;">Before</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">'@ipad'</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">$PLATFORM </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"ipad"</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>

<span style="color: #000000;"><span style="font-size: x-small;">Before</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">'@iphone'</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">$PLATFORM </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"iphone"</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Use in your feature files:</span></span></span></p>
<pre><span style="color: #000000;"><span style="font-size: small;">Given I have started application</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Implementation:</span></span></span></p>
<pre class="ruby"><span style="color: #000000;"><span style="font-size: x-small;"><strong>Given </strong></span></span><span style="color: #0000ea;"><span style="font-size: x-small;"><strong>"I have started the application"</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"><strong> </strong></span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span>
<span style="color: #000000;"> </span><span style="color: #444444;"><span style="font-size: x-small;"># ... some code</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">Given </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"\"</span></span><span style="color: #000000;"><span style="font-size: x-small;">myApp\</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">" from \"</span></span><span style="color: #000000;"><span style="font-size: x-small;">myApp</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">xcodeproj\</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">" is loaded in the #{$PLATFORM} simulator"</span></span>
<span style="color: #000000;"> </span><span style="color: #444444;"><span style="font-size: x-small;"># ... more code</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">If you wants to run iPad simulator in landscape mode:</span></span></span></p>
<pre class="ruby"><span style="color: #500000;"><span style="font-size: x-small;"><strong>def</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> switch_ipad_to_landscape</span></span>
<span style="color: #500000;"> <span style="font-size: x-small;"><strong>if</strong></span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">get_ipad_orientation </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">==</span></span><span style="color: #000000;"><span style="font-size: x-small;"> PORTRAIT</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;">   <span style="font-size: x-small;">rotate_simulator_left</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">where</span></span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong> </strong></span></span><span style="color: #000000;"><span style="font-size: x-small;">get_ipad_orientation </span></span><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">is some application specific method to decide if the simulator is in portrait or landscape mode.</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: Arial, sans-serif;"><span style="font-size: medium;">Running iCuke tests on Hudson server</span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">It’s really nice to be able to run your test suite at given intervals, or when you commit to the source code repository. To run your iCuke tests on Hudson (which is a popular continuous integration build server) you must start your iPhone simulator from a terminal window. This is easiest to do by launching an AppleScript from Hudson. </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Below are two scripts, one AppleScript and one shell script, that I used to run my iCuke tests from Hudson. </span></span></span></p>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">- run_cuke.scpt</span></span></span></p>
<pre><span style="color: #5a5c00;"><span style="font-size: x-small;">--</span></span><span style="color: #000000;"><span style="font-size: x-small;"> run_cuke.scpt</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>tell</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> application </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Finder"</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>set</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> my_folder_path to container of </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">path to me</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span><span style="color: #000000;"><span style="font-size: x-small;"> as </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>text</strong></span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>set</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> posixPath to POSIX path of </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>file</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> my_folder_path</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>set</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> scriptPath to posixPath </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">&amp;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"cuke.sh"</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">end </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>tell</strong></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>tell</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> application </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Terminal"</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">activate</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">do script scriptPath</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">end </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>tell</strong></span></span>
<span style="color: #000000;"><span style="font-size: x-small;">delay </span></span><span style="color: #246b00;"><span style="font-size: x-small;">1200</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">--</span></span><span style="color: #000000;"><span style="font-size: x-small;"> it should be enough to finish all tests</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>set</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> logscript to </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"grep -c FAILED "</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">&amp;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> posixPath </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">&amp;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"cuke.log"</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">&amp;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">" | cat"</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>set</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> cuke_failed to do shell script logscript</span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>if</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> cuke_failed </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">&gt;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #000000;"><span style="font-size: x-small;"> then</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>error</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Cucumber tests failed"</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">end </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>if</strong></span></span>
<span style="color: #000000;"><span style="font-size: x-small;">try </span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">--</span></span><span style="color: #000000;"><span style="font-size: x-small;"> do not leave terminals </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>after</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> test run</span></span>
<span style="color: #000000;"> <span style="font-size: x-small;">do shell script </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"killall 'Terminal'"</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">end try</span></span></pre>
<p><span style="color: #000000;"><span style="font-size: x-small;">- cuke.sh</span></span></p>
<pre><span style="color: #444444;"><span style="font-size: x-small;">#!/bin/bash</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">scriptpath</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;">$</span></span><span style="color: #4f005f;"><span style="font-size: x-small;">(</span></span><span style="color: #92504f;"><span style="font-size: x-small;"><strong>cd</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> ${</span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #000000;"><span style="font-size: x-small;">%</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">*</span></span><span style="color: #000000;"><span style="font-size: x-small;">} </span></span><span style="color: #4f005f;"><span style="font-size: x-small;">&amp;&amp;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #92504f;"><span style="font-size: x-small;"><strong>echo</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> $PWD</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/</span></span><span style="color: #000000;"><span style="font-size: x-small;">${</span></span><span style="color: #246b00;"><span style="font-size: x-small;">0</span></span><span style="color: #444444;"><span style="font-size: x-small;">##*/})</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">SCRIPTFOLDER</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;">`dirname </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"$scriptpath"</span></span><span style="color: #000000;"><span style="font-size: x-small;">`</span></span>
<span style="color: #92504f;"><span style="font-size: x-small;"><strong>echo</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> Cucumber script is run </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>in</strong></span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">:</span></span><span style="color: #000000;"><span style="font-size: x-small;"> $SCRIPTFOLDER</span></span>
<span style="color: #92504f;"><span style="font-size: x-small;"><strong>cd</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> $SCRIPTFOLDER</span></span>
<span style="color: #000000;"><span style="font-size: x-small;">cucumber $SCRIPTFOLDER</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/features</span></span><span style="color: #000000;"><span style="font-size: x-small;"> --format</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #000000;"><span style="font-size: x-small;">html --out $SCRIPTFOLDER</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/cuke_results</span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>.</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;">html </span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> $SCRIPTFOLDER</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/cuke</span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>.</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;">log</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Add these two scripts to your project.</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Then, add this Cucumber hook to your env.rb file:</span></span></span></p>
<pre class="ruby"><span style="color: #000000;"><span style="font-size: x-small;">After </span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>do</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;"> |s|</span></span>
<span style="color: #500000;"> <span style="font-size: x-small;"><strong>if</strong></span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">(</span></span><span style="color: #000000;"><span style="font-size: x-small;">s</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">failed?</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">)</span></span>
<span style="color: #000000;">   </span><span style="color: #210000;"><span style="font-size: x-small;">puts</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Scenario FAILED: &lt;#{s.name}&gt;"</span></span>
<span style="color: #000000;">   </span><span style="color: #210000;"><span style="font-size: x-small;">puts</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"More info about failure: SCREEN XML"</span></span>
<span style="color: #000000;">   </span><span style="color: #210000;"><span style="font-size: x-small;">puts</span></span><span style="color: #000000;"><span style="font-size: x-small;"> screen</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">.</span></span><span style="color: #000000;"><span style="font-size: x-small;">xml</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>else</strong></span></span>
<span style="color: #000000;">   </span><span style="color: #210000;"><span style="font-size: x-small;">puts</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"Scenario PASS: &lt;#{s.name}&gt;"</span></span>
<span style="color: #000000;"> </span><span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span>
<span style="color: #500000;"><span style="font-size: x-small;"><strong>end</strong></span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">On Hudson, create a new job and copy the configuration from your project's existing job.</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Configure job: </span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">add to description:</span></span></span></p>
<pre><span style="color: #bc00d7;"><span style="font-size: x-small;">&lt;</span></span><span style="color: #000000;"><span style="font-size: x-small;">a href</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/hudson/job/Helios_Cuke/ws/cuke_results</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">.html"</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span><span style="color: #000000;"><span style="font-size: x-small;">Cucumber Results</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&lt;</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/a</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span>
<span style="color: #bc00d7;"><span style="font-size: x-small;">&lt;</span></span><span style="color: #000000;"><span style="font-size: x-small;">b</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">|</span></span><span style="color: #000000;"><span style="font-size: x-small;"> </span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&lt;</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/b</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span>
<span style="color: #bc00d7;"><span style="font-size: x-small;">&lt;</span></span><span style="color: #000000;"><span style="font-size: x-small;">a href</span></span><span style="color: #5a5c00;"><span style="font-size: x-small;">=</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">"</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/hudson/job/Helios_Cuke/ws/cuke</span></span><span style="color: #0000ea;"><span style="font-size: x-small;">.log"</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span><span style="color: #000000;"><span style="font-size: x-small;">Debug</span></span><span style="color: #500000;"><span style="font-size: x-small;"><strong>.</strong></span></span><span style="color: #000000;"><span style="font-size: x-small;">log</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&lt;</span></span><span style="color: #20003c;"><span style="font-size: x-small;">/a</span></span><span style="color: #bc00d7;"><span style="font-size: x-small;">&gt;</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">add build step (execute shell):</span></span></span></p>
<pre><span style="color: #000000;"><span style="font-size: x-small;">osascript ${WORKSPACE}/run_cuke.scpt</span></span></pre>
<p><span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">Of course you can change all scripts according your needs.</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">At the end you should have your iCuke tests running on Hudson and you will get both a nice test report in HTML and the debug output as a plain text.</span></span></span><br />
<span style="color: #000000;"><span style="font-family: 'Times New Roman', serif;"><span style="font-size: small;">There is a lot of potential for doing automated feature tests for iOS using Cucumber and with iCuke and the additions above you’ll hopefully be well on your way for doing BDD in your next iOS project!</span></span></span><br />
<script src="js/shCore.js">// <![CDATA[
  mce:0
// ]]&gt;</script> <script src="js/shBrushCSharp.js">// <![CDATA[
  mce:1
// ]]&gt;</script><br />
<script src="js/shBrushXml.js">// <![CDATA[
  mce:2
// ]]&gt;</script> <script type="text/javascript">// <![CDATA[
  mce:3
// ]]&gt;</script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/02/11/cucumber-tests-on-iphoneipad/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>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>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>The BROWSABLE category revealed</title>
		<link>http://blog.jayway.com/2009/09/24/the-browsable-category-revealed/</link>
		<comments>http://blog.jayway.com/2009/09/24/the-browsable-category-revealed/#comments</comments>
		<pubDate>Thu, 24 Sep 2009 08:58:56 +0000</pubDate>
		<dc:creator>Mattias Rosberg</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1932</guid>
		<description><![CDATA[Assume that you on your desktop computer browse to a web page with the following page source Clicking on the first link you expect your browser to start a new tab and navigate to the url that was specified in the href. If you click on the second link you would expect that the browser [...]]]></description>
			<content:encoded><![CDATA[<p>Assume that you on your desktop computer browse to a web page with the following page source</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/shit.png" alt="shit" title="shit" width="417" height="102" class="aligncenter size-full wp-image-1940" /></p>
<p>Clicking on the first link you expect your browser to start a new tab and navigate to the url that was specified in the href. If you click on the second link you would expect that the browser opens up your favourite email client. The third link would probably just give you an error message since the browser has no idea how to react on a link like <b>foo://my.test.com</b></p>
<p>On Android we can control how the device should react when the user clicks on a link in the web browser, or more specific control which Activity should be started. Every time the user clicks on a link the browser sends an intent to the platform with the following content.<br />
<code><br />
action = android.intent.action.VIEW<br />
category = android.intent.category.BROWSABLE<br />
data = the text from the href tag<br />
</code><br />
If we navigate to a web page with the following page source on our Andoid device we could expect a few interesting things to happen when we click on the links.</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/shit2.png" alt="shit2" title="shit2" width="414" height="106" class="aligncenter size-full wp-image-1941" /></p>
<p>The first link will generate an intent with the following information<br />
<code><br />
action = android.intent.action.VIEW<br />
category = android.intent.category.BROWSABLE<br />
data = "tel:123456"<br />
</code><br />
This will start the Dialer application and preset the phone number to 123456.</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/device.png" alt="device" title="device" width="320" height="480" class="aligncenter size-full wp-image-1955" /></p>
<p>Clicking on the second link will not surprisingly open up the email client in your device with a preset receiver address. What about clicking on the third link? Well, by default it would just return a <strong>"page not available"</strong> error message in the browser. The intent sent from the browser will look like this<br />
<code><br />
action = android.intent.action.VIEW<br />
category = android.intent.category.BROWSABLE<br />
data = "foo://my.test.com"<br />
</code><br />
This means that if we install an Activity with the following IntentFilter</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/intentfilter.png" alt="intentfilter" title="intentfilter" width="524" height="110" class="aligncenter size-full wp-image-1962" /></p>
<p>this Activity will start when the user clicks on the third link. Pretty cool, isn't it?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/09/24/the-browsable-category-revealed/feed/</wfw:commentRss>
		<slash:comments>6</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>Working with SD cards in the Android emulator</title>
		<link>http://blog.jayway.com/2009/04/22/working-with-sd-cards-in-the-android-emulator/</link>
		<comments>http://blog.jayway.com/2009/04/22/working-with-sd-cards-in-the-android-emulator/#comments</comments>
		<pubDate>Wed, 22 Apr 2009 09:05:20 +0000</pubDate>
		<dc:creator>Mårten Österberg</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[sdk]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1537</guid>
		<description><![CDATA[Working with external storage in the Android emulator could be a little tricky and the documentation is not easy to find. I'll try to give a brief walk through of the steps needed to create a SD card image, mount the image in Linux, put content on it and use it in the emulator. Creating [...]]]></description>
			<content:encoded><![CDATA[<p>Working with external storage in the Android emulator could be a little tricky and the documentation is not easy to find. I'll try to give a brief walk through of the steps needed to create a SD card image, mount the image in Linux, put content on it and use it in the emulator. </p>
<p><strong>Creating a SD card image</strong><br />
In both the 1.1 and 1.5 version of the SDK there is a tool called mksdcard located in the <code>SDK Install Dir/tools</code> folder. Simply run </p>
<pre class="bash">./mksdcard 128M my128MbCard</pre>
<p>to create a 128Mb SD card with the name my128MbCard.</p>
<p><strong>Mounting a SD card image in Linux</strong><br />
To be able to put content on to the card you can mount the card in Linux. It will then simply appear as a folder in the filesystem.<br />
First make a directory in the /media folder:
<pre class="bash"><span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">mkdir</span> /media/mycard</pre>
<p>Then mount the card as a <a href="http://en.wikipedia.org/wiki/Loop_device">loopback device</a>:
<pre class="bash"><span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">mount</span> -o loop my128MbCard /media/mycard</pre>
<p><strong>Adding content to the card</strong><br />
With content we usually mean media content like images and videos. Images and videos are located in a folder called <code>/dcim/Camera</code>. You could of course add any content to the card. When you are done copying your files be sure to umount the card otherwise it will not be usable from the emulator.
<pre class="bash"><span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">umount</span> /media/mycard/</pre>
<p><strong>Using the card in the emulator</strong><br />
Google added something called Android Virtual Device (AVD) to the SDK 1.5. To create a new AVD using our newly created SDcard image run the following:
<pre class="bash">./android create avd --name myAVD --target <span style="color: #000000;">2</span> --sdcard my128MbCard</pre>
<p>Target 2 means that we want to use the 1.5 API features in the device. Now we simply fire up the emulator and start using our content:
<pre class="bash">./emulator -avd myAVD</pre>
<p>More information about the new SDK can be found here: <a href="http://developer.android.com/sdk/preview/">SDK</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/04/22/working-with-sd-cards-in-the-android-emulator/feed/</wfw:commentRss>
		<slash:comments>32</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>Layout resources in Android</title>
		<link>http://blog.jayway.com/2009/03/26/layout-resources-in-android/</link>
		<comments>http://blog.jayway.com/2009/03/26/layout-resources-in-android/#comments</comments>
		<pubDate>Thu, 26 Mar 2009 15:51:59 +0000</pubDate>
		<dc:creator>Mattias Rosberg</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1382</guid>
		<description><![CDATA[One thing that often confuses developers new to the Android platform is the handling of layout resources. The xml files describing the layouts are magically transfered into a more efficient binary format behind the scenes and hidden away - leaving the developer with a static reference to the resources via the R.java file. By using [...]]]></description>
			<content:encoded><![CDATA[<p>One thing that often confuses developers new to the Android platform is the handling of layout resources. The xml files describing the layouts are magically transfered into a more efficient binary format behind the scenes and hidden away - leaving the developer with a static reference to the resources via the R.java file.</p>
<p>By using the<code> setContentView(int layoutResId)</code> method of the <code>Activity</code> class your layout will be displayed on the screen. Behind the scenes the Android platform is creating all the view objects contained in your layout xml file provided to the <code>setContentView(int layoutResId)</code> method. This process of creating view objects out of layout resources is referred to as layout inflation.</p>
<p>So far so good. This means that before the <code>setContentView(int layoutResId)</code> method is called the <code>findViewById(int resId)</code> method will return null for any view references in the layout, causing some potential <code>NullpointerExceptions</code>. </p>
<pre class="java">@Override
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> onCreate<span style="color: #66cc66;">&#40;</span>Bundle savedInstanceState<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006600;">onCreate</span><span style="color: #66cc66;">&#40;</span>savedInstanceState<span style="color: #66cc66;">&#41;</span>;
&nbsp;
   EditText addressField = <span style="color: #66cc66;">&#40;</span>EditText<span style="color: #66cc66;">&#41;</span> findViewById<span style="color: #66cc66;">&#40;</span>R.<span style="color: #006600;">id</span>.<span style="color: #006600;">address</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//To early!! Will return null</span>
   setContentView<span style="color: #66cc66;">&#40;</span>R.<span style="color: #006600;">layout</span>.<span style="color: #006600;">main</span><span style="color: #66cc66;">&#41;</span>;
   <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AButton+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Button</span></a> button = <span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AButton+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Button</span></a><span style="color: #66cc66;">&#41;</span> findViewById<span style="color: #66cc66;">&#40;</span>R.<span style="color: #006600;">id</span>.<span style="color: #006600;">launchMap</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
   addressField.<span style="color: #006600;">setText</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Some Text&quot;</span><span style="color: #66cc66;">&#41;</span>;	<span style="color: #808080; font-style: italic;">//NullPointerException</span>
   button.<span style="color: #006600;">setText</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Some other text&quot;</span><span style="color: #66cc66;">&#41;</span>;	<span style="color: #808080; font-style: italic;">//No problem</span>
<span style="color: #66cc66;">&#125;</span></pre>
<p>To avoid these errors it's a good habit to place the <code>setContentView(int layoutResId)</code> method call at the very top of the <code>onCreate()</code> method.</p>
<p>In some cases you will have to do the layout inflation by yourself, i.e. when you want to set a custom view to a <code>Dialog</code> or a <code>Toast</code>. To inflate a view you use the <code>LayoutInflater</code> class. There's a number of different ways to get a handle to a <code>LayoutInflater</code>:</p>
<pre class="java">LayoutInflater inflater = <span style="color: #66cc66;">&#40;</span>LayoutInflater<span style="color: #66cc66;">&#41;</span>context.<span style="color: #006600;">getSystemService</span><span style="color: #66cc66;">&#40;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AContext+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Context</span></a>.<span style="color: #006600;">LAYOUT_INFLATER_SERVICE</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
LayoutInflater inflater = LayoutInflater.<span style="color: #006600;">from</span><span style="color: #66cc66;">&#40;</span>context<span style="color: #66cc66;">&#41;</span>;</pre>
<p>To actually create the view object you use the inflate() method of the LayoutInflater. In the most straightforward form this method has the signature:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AView+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">View</span></a>  inflate<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> resource, ViewGroup root<span style="color: #66cc66;">&#41;</span></pre>
<p>Note that the resource is referring to a layout xml file resource, NOT the id of the view object that you want to inflate. First inflate the layout resource and then get a handle to the view object by using the <code>findViewById(int resId)</code> method.</p>
<p>The second attribute allows you to specify a <code>ViewGroup</code> object to be the root view of the inflated object(s) specified by your layout xml file. This means that the inflated view object(s) are attached as child views on the specified root <code>ViewGroup</code> object. Setting this value to null will simply return the inflated view object(s) without attaching them to a root view. </p>
<pre class="java">EditText fooField = <span style="color: #66cc66;">&#40;</span>EditText<span style="color: #66cc66;">&#41;</span> findViewById<span style="color: #66cc66;">&#40;</span>R.<span style="color: #006600;">id</span>.<span style="color: #006600;">foo</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//To early!! Will return null</span>
LinearLayout myRoot = <span style="color: #000000; font-weight: bold;">new</span> LinearLayout<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AView+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">View</span></a> itemView = inflater.<span style="color: #006600;">inflate</span><span style="color: #66cc66;">&#40;</span>R.<span style="color: #006600;">layout</span>.<span style="color: #006600;">layout_details</span>, myRoot<span style="color: #66cc66;">&#41;</span>;  <span style="color: #808080; font-style: italic;">//from layout_details.xml</span>
EditText barField = <span style="color: #66cc66;">&#40;</span>EditText<span style="color: #66cc66;">&#41;</span> findViewById<span style="color: #66cc66;">&#40;</span>R.<span style="color: #006600;">id</span>.<span style="color: #006600;">bar</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">//Now we have an object</span></pre>
<p>In this example the inflate method returns the mRoot object with the view objects contained in the layout_details.xml file attached as child views. So itemView and myRoot is actually referring to the same physical object. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/26/layout-resources-in-android/feed/</wfw:commentRss>
		<slash:comments>8</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>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>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>
		<item>
		<title>Java ME Logging over Bluetooth using MicroLog</title>
		<link>http://blog.jayway.com/2008/12/17/java-me-logging-over-bluetooth-using-microlog/</link>
		<comments>http://blog.jayway.com/2008/12/17/java-me-logging-over-bluetooth-using-microlog/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 16:17:25 +0000</pubDate>
		<dc:creator>Henrik Larne</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[bluetooth]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=604</guid>
		<description><![CDATA[When developing in Java ME and wanting to support several different devices, you wil no doubt run into problems with devices behaving differently. In some cases it is only the appearance that changes and in others the actual functionality varies or breaks. The first step in solving this is to run your Midlet in the [...]]]></description>
			<content:encoded><![CDATA[<p>When developing in Java ME and wanting to support several different devices, you wil no doubt run into problems with devices behaving differently. In some cases it is only the appearance that changes and in others the actual functionality varies or breaks. The first step in solving this is to run your Midlet in the emulators for the devices that you want to support and hopefully you will be able to solve some of the problems here, but unless you are really lucky there will be some problems remaining that needs to be debugged on the actual device. Depending on which device it is you might be able to run On Device Debugging  to solve it, but in many cases you don't have that option or the On Device Debugger is not stable enough. So now you are left with logging as your only tool to debug the midlet. Logging on a small screen device with very limited ram is not trivial however. </p>
<p>What you really want is to have the midlet write the log to your development PC instantaneously and free of charge, then you can log whatever you want to pinpoint your bug. This could be accomplished by logging over Bluetooth. Previously you had to write your own code to handle the logging and Bluetooth communication as well as a server to which the midlet connects and sends the log messages, but now there is a powerful logging framework for Java ME that offers this support out of the box. The framework is <a href="http://microlog.sourceforge.net">MicroLog</a> and is open source under the Apache Software License, so it is free to use as you see fit. MicroLog can be configured with one or more appenders that takes care of the logging messages and sends them to the right destination and each appender can have its own formatter to format the messages appropriately. This is very similar to log4j, so if you have used log4j before, MicroLog is very easy to learn. If you are using Maven 2 you will be happy to know that MicroLog is built using Maven 2 and is available in a public repository.</p>
<p>Setting up MicroLog to use Bluetooth and log to your PC is simple. It only requires that you setup your Logger:</p>
<pre>
private final static Logger log = Logger.getLogger(TestMidlet.class);
</pre>
<p>and that you configure it to use a <code>BluetoothSerialAppender</code>, which is done like this:</p>
<pre>
log.addAppender(new BluetoothSerialAppender());
</pre>
<p>Now your midlet is all set to start logging over Bluetooth. For a full midlet example see the following code:</p>
<pre>
package se.jayway.me;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import net.sf.microlog.Logger;
import net.sf.microlog.bluetooth.BluetoothSerialAppender;

public class TestMidlet extends MIDlet
{

	private final static Logger log = Logger.getLogger(TestMidlet.class);

	public TestMidlet()
	{
		configureMicroLog();
	}

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException
	{
		log.info("Destroying application...");
	}

	protected void pauseApp()
	{
		log.info("Pausing application...");
	}

	protected void startApp() throws MIDletStateChangeException
	{
		log.info("Starting application...");
		final TextBox textBox = new TextBox("Text", "My text", 100, 0);
		textBox.addCommand(new Command("Log", Command.SCREEN, 0));
		textBox.setCommandListener(new CommandListener() {
			private int counter;

			public void commandAction(Command c, Displayable d)
			{
				log.debug("You clicked " + counter++);
				log.debug(textBox.getString());
			}
		});
		Display.getDisplay(this).setCurrent(textBox);
	}

	private void configureMicroLog()
	{
		log.addAppender(new BluetoothSerialAppender());
	}
}
</pre>
<p>Build and deploy this midlet to your Bluetooth enabled device, supporting JSR-82, the Bluetooth API and make sure that Bluetooth is turned on.</p>
<p>Next you need to get the Bluetooth server that will receive and print the logging messages to standard out. The server is also available in a public <a href="http://microlog.sourceforge.net/repo/m2-snapshot-repository/net/sf/microlog-servers/">Maven repository</a>. Just download the version that ends with -jar-with-dependencies.jar. This file contains all its dependencies. Now make sure that your Bluetooth unit is on and discoverable on your PC. Then start the server with the following command:</p>
<pre>
java -cp microlog-servers-1.1.0-SNAPSHOT-jar-with-dependencies.jar net.sf.microlog.server.btspp.MicrologBtsppServer
</pre>
<p>You might have to change the jar file name if it is not the same as the one you downloaded, then just replace it with the file name of your own microlog-server jar file.</p>
<p>The server starts up and registers a logging service with a unique UUID that the phone will try to locate and connect to. Now start the midlet and see how it will start logging over the Bluetooth connection.</p>
<p>The first phone I tested was a SonyEricsson C905 and it worked perfectly from the start. Then I tried to use a SonyEricsson P990i and for some reason it failed to locate the logging server with the unique UUID. I was unable to determine the reason why it failed to locate the service, so instead I added support to the <code>BluetoothSerialAppender</code> to specify the url of the Bluetooth logger server. Using this and setting the server url to my PC it connected flawlessly to it and started logging. So if you experience problems when your midlet connects to the PC or if you are using multiple logger servers within the Bluetooth range of your device try specifying the server url that the <code>BluetoothSerialAppender</code> should connect to. The url of the server is shown when starting the logger server. This url does however contain a channel that is not possible to determine through the used API's, but it does start on 1 and increases. For each session I always got the same channel and it was only the next day that it changed and I got channel 2 instead, so try with 1 to start with and if that does not work increase it by one and try again. It will most likely work first or second time.</p>
<p>Now you are free to log as much as you want and do not have to restrict your logging during the development phase of your project. Neither is there a reason for writing your own Bluetooth logger, just use MicroLog.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/17/java-me-logging-over-bluetooth-using-microlog/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>iPhone Tech Talks &#8211; Stockholm</title>
		<link>http://blog.jayway.com/2008/12/09/iphone-tech-talks-stockholm/</link>
		<comments>http://blog.jayway.com/2008/12/09/iphone-tech-talks-stockholm/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 09:03:51 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[User Experience]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[sdk]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=535</guid>
		<description><![CDATA[Apple has arranged a world tour of iPhone Tech Talks, and in cold december it was Scandinavia's turn and a crew of software evangelists from Apple turned up at KTH in Stockholm for a full day of sessions. The sessions are confidential so I will keep this post vague on the technical parts, not revealing [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.apple.com">Apple</a> has arranged a world tour of <a href="http://developer.apple.com/events/iphone/techtalks/">iPhone Tech Talks</a>, and in cold december it was Scandinavia's turn and a crew of software evangelists from Apple turned up at <a href="http://www.kth.se/">KTH</a> in Stockholm for a full day of sessions.</p>
<p>The sessions are confidential so I will keep this post vague on the technical parts, not revealing any thing that might or might not come to an iPhone or iPod touch near you in the future. And I can not mention any specific sales numbers, but I do can say that any predicted numbers you might have seen; is probably an underestimation with a margin and then some.</p>
<p>The sessions where on a high level, not going too deep on technical details. Instead the sessions concentrated on the overall design philosophies, and common gotchas. For the nitty gritty details Apple engineers where available, and I missed half a session discussing the ins and outs of the UIToolbar class with Alberto Arauz. Alberto is one of the european software evangelist, and was most impressed, and interested, when I described the successful <a href="http://www.oredev.org/topmenu/program/trackmobile20.4.2c4b8bee11a31fca49e8000319.html">Mobile 2.0 track</a> at <a href="http://www.oredev.org">Øredev 2008</a>. Apple's overall impression with Scandinavia has so far been a mostly cold hand regarding anything with Apple, going as far as only six people registering for a Tech Talk in Oslo two years ago.</p>
<p>Apart from the speakers and engineers, Apple also brought a video-team. So yours truly has been intervjued about the <a href="http://www.peylow.se/">applications I have</a> on App Store, and my experience with the iPhone SDK. The video will be cut and edited for promotional purposes, and hopefully me mentioning both Malmö and Jayway will not be cut out. The odds of my short talk being included is quite good, as most developers seems to be focusing on games, not utilities as I and Jayway has done.</p>
<p>The best part to take home is not technical, just solid advice for any development, not even under NDA, and the sole point repeated by Apple over and over: <strong>Developing great applications is not about adding features!</strong> The trick is not to cram in as many features as you can, the trick is to know what features to leave out, so that time can be well spend on the key features that do make the cut. And this is tenfold as important on a mobile device where real estate is limited. A quote from Mark Twain:</p>
<blockquote><p>I apologize for writing you a long letter, but I did not have the time to write a short.</p></blockquote>
<p>Writing short, and cutting features is hard. How to decide on the features to drop or implement? Apple uses a simple technique, called a product statement. The product statement for the Photos application is for example; <em>"An easy to use photo sharing application for all iPhone users"</em>. Any feature that do not help fulfilling this statement do not make it. How about simple photo-editing? Nope, does not comply with statement. The wording of the product statement is important, by simply changing it to <em>"An easy to use photo sharing application for <u>professional photographers</u>"</em>, would be a completely new application. Only when the product statement is agreed upon, can an approved list of features be made. An omnipresent Steve Jobs approving and dismissing features, is an exaggeration, this simple method is what do the trick.</p>
<p>Now this might sound both obvious, and counterintuitive. Surely adding that last nice feature would add value? Not at the expense of a cluttered user interface, that is meant to be used while standing in line for 30 seconds. Features thought to be must haves, most of the time are not. Some features thought to be must haves are MMS and video recording. Looking at the raging success of the iPhone, it is very obvious that they are not must haves. We as software engineers must at long last learn that it truly is quality over quantity.</p>
<p>And lastly a personal reflection; from a developer's point of view the best part about iPhone SDK is that it is not an UI framework, it is an Application framework. It do not settle with providing the tools for collections, persisting data, displaying a UI, and then leave the rest of the architecture to the developers. The iPhone SDK supports all three parts of the Model-View-Controller paradigm equally well, and that is what makes it so productive.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/09/iphone-tech-talks-stockholm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android on the FreeRunner</title>
		<link>http://blog.jayway.com/2008/11/21/android-on-the-freerunner/</link>
		<comments>http://blog.jayway.com/2008/11/21/android-on-the-freerunner/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 17:01:48 +0000</pubDate>
		<dc:creator>Peter Neubauer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[oredev]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=450</guid>
		<description><![CDATA[Hi there, Øredev was great success, especially all the people and the organization - a big Thank You to Michael and Emily for making this possible, you rock! Now, it was really awesome to exchange Android games with Mike Jennings fro the Android team, and get him excited over the recent Android port to the [...]]]></description>
			<content:encoded><![CDATA[<p>Hi there,</p>
<p>Øredev was great success, especially all the people and the organization - a big Thank You to Michael and Emily for making this possible, you rock!</p>
<p>Now, it was really awesome to exchange Android games with Mike Jennings fro the Android team, and get him excited over the recent Android port to the Neo FreeRunner! Thanks Anders Hedberg for coming over to fix the FR, and to all the OpenMoko enthusiasts doing the hard work!</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2008/11/1227281553155.jpg" rel="lightbox"><img class="alignnone size-medium wp-image-451" title="Android on the NeoFreerunner" src="http://blog.jayway.com/wordpress/wp-content/uploads/2008/11/1227281553155-225x300.jpg" alt="" width="225" height="300" /></a></p>
<p>/peter neubauer</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/11/21/android-on-the-freerunner/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Give back my XMPP in Android!</title>
		<link>http://blog.jayway.com/2008/11/21/give-back-my-xmpp-in-android/</link>
		<comments>http://blog.jayway.com/2008/11/21/give-back-my-xmpp-in-android/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 16:46:25 +0000</pubDate>
		<dc:creator>Peter Neubauer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[oredev]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=443</guid>
		<description><![CDATA[Since the release of the Android SDK 1.0, people (including me) have been complaining about the lack of connectivity for the very convenient Smack API to talk to Googles GTalk servers following http://davanum.wordpress.com/2007/12/31/android-just-use-smack-api-for-xmpp/, see here. However, yesterday @Øredev, I met Mike Jennings from the Android team and together we looked into this problem over a [...]]]></description>
			<content:encoded><![CDATA[<p>Since the release of the Android SDK 1.0, people (including me) have been complaining about the lack of connectivity for the very convenient Smack API to talk to Googles GTalk servers following <a title="this tutorial" href="http://davanum.wordpress.com/2007/12/31/android-just-use-smack-api-for-xmpp/">http://davanum.wordpress.com/2007/12/31/android-just-use-smack-api-for-xmpp/</a>, see <a title="XMPP problems" href="http://groups.google.com/group/android-developers/search?hl=en&amp;group=android-developers&amp;q=xmpp&amp;qt_g=Search+this+group">here</a>.</p>
<p>However, yesterday @Øredev, I met Mike Jennings from the Android team and together we looked into this problem over a beer in the Oracle booth. Looking into the current SVN source at <a title="source" href="http://svn.igniterealtime.org/svn/repos/smack/trunk/source" target="_blank">http://svn.igniterealtime.org/svn/repos/smack/trunk/source</a>, it seemed that a fast hack to get things working (especiallly the keystore problem on the device) would be to simply disable SSL negotiation.This does of course not work for SSL stuff, but it gets you going and it is enough for talk.google.com:5222. It is enough to just disable SSL negotiation by hardcoding it away in the ConnectionConfiguration.java, and comment out everything related to java.beans and other packages that are not present on the Android platform to get things working.</p>
<p>After doing that, voila things started to work and I am now happily logging in programatically via SVN Smack again!</p>
<p>Thanks Mike for the hints, help and a great BouncingBall application!</p>
<p>For anyone intersted, I am attaching the patch.</p>
<p>/peter neubauer</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2008/11/smackdiff.zip">smackdiff</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/11/21/give-back-my-xmpp-in-android/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>LWUIT &#8211; an introduction</title>
		<link>http://blog.jayway.com/2008/05/01/lwuit-an-introduction/</link>
		<comments>http://blog.jayway.com/2008/05/01/lwuit-an-introduction/#comments</comments>
		<pubDate>Thu, 01 May 2008 13:03:46 +0000</pubDate>
		<dc:creator>Johan Karlsson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[jayview]]></category>
		<category><![CDATA[midp]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3226</guid>
		<description><![CDATA[Have you ever tried to create a business application in Java ME? The user interface toolkit provided by MIDP 2.0 is very limited. There is now an alternative toolkit available. Read on and you will learn about this new user interface toolkit. But be aware, there will be some spiffy source code and an accompanying [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Have you ever tried to create a business application in Java ME? The user interface toolkit provided by MIDP 2.0 is very limited. There is now an alternative toolkit available. Read on and you will learn about this new user interface toolkit. But be aware, there will be some spiffy source code and an accompanying screen shot! </strong></p>
<h2>What is it?</h2>
<p>The new Light Weight User Interface Toolkit (LWUIT) is a new UI toolkit for Java ME that is inspired by Swing. It is developed by Sun and it is available as open source (GNU GPL V2). The early access version runs on MIDP 2.0, but the upcoming versions will be available for other Java ME profiles as well. This opens up the possibility to write the same user interface code for mobile devices ranging from very simple mobile phones to advanced PDAs. The feature list for LWUIT is impressive. It includes features like:</p>
<ul>
<li> pluggable look-and-feels with themes
<li> layout managers
<li> touch screen support
<li> fonts
<li> resources bundles
<li> transitions
<li> 3D integration
</ul>
<p>The developer could create a customized look-and-feel by creating a subclass to<br />
the LookAndFeel or DefaultLookAndFeel class, similar to Swing. On top of that it is possible to set a theme. A theme is defined in a Java property file. You use a key in the property file that is similar to a CSS selector. For example, Button. bgColor=ff0000 is used to set all button backgrounds to red. </p>
<p>The developer has access to layout managers like BorderLayout, FlowLayout,<br />
GridLayout and others known from Swing. The GridBagLayout is not present, but I doubt that many will miss it. If you ever tried it, you know what I mean. The touch screen support is also an important feature, since many mobile devices today has touch screens. </p>
<p>The support for fonts in MIDP is rather limited. In LWUIT it is possible to use your own fonts. You use the resource editor to convert your fonts from your favorite operating system, and the selected fonts are converted and bundled in your jar file. The editor is also used for localization strings, images and themes.</p>
<p>A transition is used when switching between different forms, i.e. screens, and brings a nice touch to the UI. If the phone has an implementation of JSR-184:<br />
Mobile 3D Graphics API for J2ME, it is possible to make a cube transition. The 3D integration let us show 3D models in our 2D interface. This is realized by loading an M3G file. The M3G format is 3D format that is optimized for Mobile<br />
Devices (for more details see the references). By connecting each M3G object to a LWUIT graphic object it is possible to implement advanced logic for your 3D interface. The M3G is supported by JSR-184. A nice side effect of this is that the 3D graphics could be rendered by your 3D hardware on your mobile device. Support for SVG is also announced, which will give even more possibilities when writing UIs for mobile devices. </p>
<h2>How to use it</h2>
<p>And now for the moment you all have been waiting for. The code! We start with<br />
the classical “Hello JayView” example. The code looks like this:</p>
<pre>package se.jayway.javame.lwuit.test; 

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException; 

import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.animations.Transition3D;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.util.Log; 

public class HelloJayViewMIDlet extends MIDlet implements ActionListener { 

  private Command exitCommand;
  private Command nextCommand;
  private Form formTwo;
  private Button button; 

  protected void startApp() throws MIDletStateChangeException {
    Display.init(this); 

    Form formOne = new Form(”Hello”);
    formOne.setLayout(new BorderLayout()); 

    Label label = new Label(”JayView”);
    label.setAlignment(Label.CENTER);
    formOne.addComponent(BorderLayout.CENTER, label); 

    button = new Button(”Help Me”);
    button.addActionListener(this);
    formOne.addComponent(BorderLayout.SOUTH, button); 

    exitCommand = new Command(”Exit”);
    formOne.addCommand(exitCommand);
    nextCommand = new Command(”Next->”);
    formOne.addCommand(nextCommand);
    formOne.setCommandListener(this); 

    formOne.setTransitionOutAnimator(Transition3D.createCube(750, false)); 

    formTwo = new Form(”Hello Again”);
    // TODO: Add components and Commands to fromTwo
    formOne.show();
  } 

  protected void destroyApp(boolean unconditional)
      throws MIDletStateChangeException {
    // TODO: Add code that release all out resource
  } 

  protected void pauseApp() {
    // TODO: Do stuff when we pause the MIDlet
  } 

  /**
   * Implementation of the &lt;code&gt;ActionListener&lt;/code&gt; interface.
   */
  public void actionPerformed(ActionEvent event) {
    Log.p(”actionPerformed()”, Log.INFO);
    Command command = event.getCommand(); 

    if (command == exitCommand) {
      notifyDestroyed();
    } else if (command == nextCommand) {
      formTwo.show();
    } 

    Object source = event.getSource();
    if(source == button){
      // TODO: Show some help to the user
    }
  } 

} </pre>
<p>At a first glance this looks like a normal MIDP application. You may recognize<br />
Command, Form & Display classes. If you look close, you notice that these are<br />
not the same classes. They are in fact classes found in the LWUIT toolkit and<br />
actually work a little bit different. This is where the similarities end. </p>
<p>Let us take a look at the differences instead. We start by initializing our display<br />
with Display.init(). This takes a reference to our MIDlet object, which in turn<br />
takes care of all the initialization. We continue by creating a Form object which<br />
occupies the whole screen. The Form object is populated with a Label that<br />
is placed in center of the screen. The alignment of the label is set to center.<br />
As you can see we have good control of the placement of our components,<br />
unlike MIDP where you are dependent on the underlying implementation. A<br />
Label object can have a text and/or an icon. When we have both, it is of course<br />
possible to align the text relative to the icon.</p>
<p>A Button object is like a button that you are used to from your desktop<br />
applications. However it is something that is not found in MIDP. Just<br />
like a Label you could have an icon and/or a String in each Button. You<br />
add an ActionListener to the Button, which in our case is the MIDlet that<br />
implements the ActionListener interface. The ActionListener consists of the<br />
actionPerfomed() method, which is like Swing, not like MIDP. The Button is<br />
added to the south of the Form. It occupies the whole width of the Form since<br />
that is how BorderLayout works like. In a real world example we could use<br />
nested layouts to fix this problem. It should be noted that there are still some<br />
peculiarities in this early access release. For example it is possible set the colors<br />
of a Label object, but not on a Button object. </p>
<p>The next thing to do is to create our Command objects. Each Command<br />
object corresponds to an item in one of the menus. We add them to the Form.<br />
The action could be the user pressing a button or selecting a command. The<br />
Command that triggered a call to actionPerformed() is fetched using the event.<br />
getCommand() method. We use an if-else statement to check which Command<br />
that was used. If you have more Command objects than this, you should consider<br />
using the Command pattern as described in JayView 10, Take Command in<br />
Java ME. We must also check if the event was received from the button. We<br />
get the source with a call to event.getSource(), just like in Swing. We finish off<br />
the actionPerformed() method by checking if the event was received from our<br />
button. </p>
<p>In our example we call notifyDestroyed() to signal to the platform that we are<br />
finished. In the other case we show our second Form. By the way, did you notice<br />
that we did call a method called setTransitionOutAnimator()? This is used to<br />
create a 3D cube transition when switching between the first and the second<br />
Form. It is not something that is available in MIDP.</p>
<p>The LWUIT toolkit contains some utilities like a logging utility, as seen in<br />
actionPerformed(). This is an easy way to do some simple logging. But I would<br />
recommend that you use a proper Java ME logging framework, like Microlog.<br />
<img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/Picture-62.png" alt="Voila! This is how it looks like in an emulator." title="Voila! This is how it looks like in an emulator." width="199" height="363" class="alignnone size-full wp-image-3227" /></p>
<p>Voila! This is how it looks like in an emulator.</p>
<h2>Some Final Words </h2>
<p>My first impression of LWUIT was very positive. Since I consider myself a fluent<br />
writer in “Swinglish”, I was happy when I could re-use my programming skills<br />
for LWUIT. Many Swing lovers will have the same feeling, I guess. Since it is<br />
open source I think that the toolkit could reach a wide audience and hopefully<br />
it will have a large community with all its benefits. A big advantage is that we<br />
now have a large set of components available. One thing missing in MIDP is<br />
a tabbed pane, which is included in LWUIT. Another thing to consider is of<br />
course the size that the LWUIT adds to your application. The full size of the<br />
jar-file is about 230 KB. In practice you will not use all the classes, and with<br />
an obfuscator the size will be reduced even further. According to the LWUIT<br />
development team the average overhead when using LWUIT is around 100 KB.<br />
In any case an obfuscator should always be part of your Java ME toolbox. </p>
<p>On the downside is the performance. I have tested it on a Sony Ericsson W910,<br />
which contains a high performance JVM. Although some of the components<br />
were not as fast as I would like them to be it has to be pointed out that this is<br />
only an early access release and the performance will probably be much better.<br />
Another possible disadvantage is the type of open source license that has been<br />
chosen. Many people would argue that the Apache License would be a better<br />
license. However this is a minor issue. </p>
<p>I think that this could be a practical alternative when developing MIDP<br />
applications. Its success depends on the performance and a large developer<br />
community. If both of these get satisfied we will see many mobile applications<br />
developed with LWUIT, at least according to my opinion. </p>
<h2>References</h2>
<li> <a href="http://lwuit.dev.java.net/">The LWUIT homepage</a>
<li> <a href="http://www.gnu.org/licenses/gpl-2.0.html">GNU GPL V2</a>
<li> <a href="http://www.jcp.org/en/jsr/detail?id=184 ">JSR 184: Mobile 3D Graphics API for J2ME</a>
<li> <a href="http://en.wikipedia.org/wiki/M3G">M3G on Wikipedia</a>
<li> <a href="http://today.java.net/pub/a/today/2008/05/15/javamobility-podcast46.html">Java Mobility Podcast 46: LWUIT - Lightweight UI Toolkit</a>
<li> <a href="http://microlog.sf.net/">The MicroLog homepage  </a><br />
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/05/01/lwuit-an-introduction/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

