<?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; iphone</title>
	<atom:link href="http://blog.jayway.com/tag/iphone/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 28 Jan 2012 15:53:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Developers exploratory testing &#8211; Expanding its value</title>
		<link>http://blog.jayway.com/2011/12/17/developers-exploratory-testing-expanding-its-value/</link>
		<comments>http://blog.jayway.com/2011/12/17/developers-exploratory-testing-expanding-its-value/#comments</comments>
		<pubDate>Sat, 17 Dec 2011 16:55:48 +0000</pubDate>
		<dc:creator>Sigurdur Birgisson</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[DET]]></category>
		<category><![CDATA[developers exploratory testing]]></category>
		<category><![CDATA[exploratory testing]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[ipad]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[team]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11624</guid>
		<description><![CDATA[There is a common practice in our company to perform Developers Exploratory Testing sessions, explained by my colleague Davor here. The cool thing is that this way of performing higher level testing has actually become accepted by our developers, and they really enjoy it. In my current work of developing our organization wide practices for quality, I have [...]]]></description>
			<content:encoded><![CDATA[<p>There is a common practice in our company to perform Developers Exploratory Testing sessions, explained by my colleague Davor <a href="http://www.stickyminds.com/sitewide.asp?function=DETAILSIDX&amp;tvniu=1&amp;sqry=*Z(SM)*J(ART)*R(createdate)*&amp;ObjectId=17003&amp;ObjectType=ART&amp;sidx=1">here</a>. The cool thing is that this way of performing higher level testing has actually become accepted by our developers, and <a href="http://blog.jayway.com/2010/10/11/three-reasons-for-me-as-a-developer-to-love-developer-exploratory-testing/">they really enjoy it</a>.</p>
<p>In my current work of <a href="http://blog.jayway.com/2011/12/01/organization-wide-test-strategy-step1-deriving-our-quality-values/">developing our organization wide practices for quality</a>, I have made a deep dive into how DET is carried out on a regular basis. What I have seen is that DET is accepted and acknowledged as a valuable practice, however it is not really carried out in its full potential. There are many details and aspects of it to work on, especially regarding reporting and follow-up.</p>
<p>The other day I was asked to help one of our teams with a DET session. <span id="more-11624"></span>As they are familiar with the approach, I wanted to expand their view on its potential through light weight note taking and showed them an example of a <a href="https://docs.google.com/document/d/1Ew5B868XB0-S5vq6KfxNi4tck9szJ2zZEXjLq4XpbAs/edit">very basic session template I like to use</a>. I also explained the intentions of having bugs and issues separated as well as how I do with test notes and the summary. We decided to use a whiteboard instead and put stickies with issues and bugs on there for visualization. We spoke about the mission and decided on two different areas to focus on. The app is an iOS app where a new component is used in the app core functionality for iOS5.</p>
<p>The four of us paired into two teams with some different iOS devices and tested for about 45 minutes. We found quite a few issues and bugs that were put on the whiteboard, but not so much notes about which areas we covered. Of course, by looking at the issues you might get a hint of what areas have been covered, but how much? We also quite quickly noted that we had to tag each issue with the test environment (iOS version and device), since they differed quite a lot. Most of the things found were considered bugs to fix, which is also not always the case in all projects or settings. It usually depends on the customer and the relationship to them, as well as having a decision maker on this present during testing. In this project, the scrum master/tech lead which was present knows the customer well enough to make those judgements.</p>
<h3>But what about the learnings?</h3>
<p>After the session debrief I got into a meta-debrief, discussing the outcome compared to my introduction about reporting. At first there was not very much understanding of why having test notes is valuable, but this shifted a little during our discussion. "While our smaller projects change that rapidly, even storing test notes might be waste" is a motivation I will take with me. I explained a common scenario of being asked what was tested and with what configuration. It could also be valuable for future test sessions to know what parts of a functionality was covered and when this was tested before. I also like to emphasize the possibility to explain current functionality which might not be explicitly stated in requirements.</p>
<p>The team was happy with the experience and I got some more input on how to improve the value of our DET sessions. I am not going to abandon the reporting, but I need to find a way of combining the fun part of interacting between pairs through the collaborative setting of the whiteboard. This actually helped getting attention on the issues in the debrief.</p>
<p>And then the developers actually got their own ideas of what a session note taking tool should look like to suit their needs, this is how they sketched it out after the session. I would explore some other possibilities before building our own for example <a href="http://testing.gershon.info/reporter/">RapidReporter</a> or <a href="http://code.google.com/p/sessionweb/">SessionWeb</a>, but it is really cool that the meta-discussion could trigger the further thinking about the problem. Other aspects of the problem with collective knowledge transfers I wrote about <a href="http://happytesting.wordpress.com/2011/06/15/collective-note-taking-more-value-from-your-test-notes/">here</a>.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/photo.jpg" rel="lightbox"><img class="aligncenter size-medium wp-image-11626" title="Sketchup of test note taking tool" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/photo-224x300.jpg" alt="" width="224" height="300" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/17/developers-exploratory-testing-expanding-its-value/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Invoke any Method on any Thread</title>
		<link>http://blog.jayway.com/2011/08/08/invoke-any-method-on-any-thread/</link>
		<comments>http://blog.jayway.com/2011/08/08/invoke-any-method-on-any-thread/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 08:03:16 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tutorial]]></category>

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

@implementation CWMainProxy

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

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

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

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

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

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

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

static NSMutableDictionary* cw_recoveryErrors = nil;

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

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

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

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

@end</pre>
<h3>Conclusion</h3>
<p>The clean separation of exceptions and errors help you as a developer to catch programming errors during development and with unit tests, and also handle errors of interest to the end users in a standardized and uniform way. The very nature of <code>NSError</code> encourages developers to write descriptive error messages that end users can understand and make informed discussions about. Errors are unavoidable in any application of non-neglectable complexity, gracefully handling these errors gives an aura of quality and ensures happy users. Happy users means better sales.</p>
<p>Full source code to the examples in this post, including some more convenience methods can be <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/10/UIAlertView+CWErrorHandler1.zip'>downloaded here</a>, and are released under the Apache 2 open source license. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/10/13/exceptions-and-errors-on-ios/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Iphone app testing and bugs</title>
		<link>http://blog.jayway.com/2010/09/21/iphone-app-testing-and-bugs/</link>
		<comments>http://blog.jayway.com/2010/09/21/iphone-app-testing-and-bugs/#comments</comments>
		<pubDate>Tue, 21 Sep 2010 20:41:33 +0000</pubDate>
		<dc:creator>Sigurdur Birgisson</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[bugs]]></category>
		<category><![CDATA[exploratory testing]]></category>
		<category><![CDATA[iphone]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6328</guid>
		<description><![CDATA[Some 1-1,5 years back, when the iPhone 3G had made such a success in Sweden, to develop apps for it got to be a hot potato in the software development business. Everyone wanted an iPhone app for their product/company, and we were not late to adopt this need and make it happen. Now we are [...]]]></description>
			<content:encoded><![CDATA[<p>Some 1-1,5 years back, when the iPhone 3G had made such a success in  Sweden,  to develop apps for it got to be a hot potato in the software  development business. Everyone wanted an iPhone app for their  product/company, and we were not late to adopt this need and make it  happen. Now we are pretty good at developing cocoa apps.</p>
<p>From the testing perspective, I started to look at if testing on  iPhone was different from any other software testing. I started off  asking a senior app developer about his view on this, and got this  answer in an email:</p>
<blockquote><p>Iphone has very many complete components, which means  that the developer doesn't have to invent the wheel all the time. These  complete components are well tested by Apple.</p>
<p>Focus on iPhone app testing should be on the levels of<br />
1. Application logic<br />
2. Verifying that the Apple interface guidelines is followed.<br />
3. Input validation</p></blockquote>
<p>As a tester, this "easy to develop, easy to test" mentality should in  my perspective trigger all bells and whistles as warning signs.</p>
<p>To cut to the point, having this background and tested some of the  apps developed by my friends, I want to say that testing iphone apps is  nothing different nor creates different kind of bugs than when testing  other software. Some of the different type of bugs that can be shown  through screenshots is shown here. The number of times I have gotten  apps to crash is facts that I actually don't know, since it happens all  the time.</p>
<p>For clarification, the environment is a regular iPhone 3G with the  (at the time of any bug/screenshot) latest iOS3 software. I haven't  upgraded to iOS4 yet because of the risk of the phone getting slower  than it already is. My dad complained about this just couple of weeks  ago after upgrade. Neither have I jailbroken the phone, and I am not a  very big consumer of apps, which means that I have a very limited amount  of apps on my phone.</p>
<p>The reasons that I point out for the bugs are just guesses from my  point, and should be taken like guesses as well =)</p>
<h3>Application UI issues</h3>
<p>Application UI issues include Tweetdeck where sending a tweet  progress bar is shown on top of the tweet search column header. Another  UI issue which I have seen in many other apps include that the  default(?) error popup message has been left as default without  describing the usage error that the user in this case forgot to fill out  some mandatory fields.</p>
<p><img src="http://happytesting.files.wordpress.com/2010/09/img_0709.png" alt="Tweetdeck UI" width="275" height="411" /> <img src="http://happytesting.files.wordpress.com/2010/09/img_0874.png" alt="Default error message" width="275" height="412" /></p>
<h3>Application logic</h3>
<p>I am actually not sure if these logic issues should be on client or  server side, but my guess is that its client side. The question here is  if its a coincidence that two different apps encounter null as profile  name when looking at the profile pages. A wild guess is that they both  use the same kind of ”complete components” in development.</p>
<p><img src="http://happytesting.files.wordpress.com/2010/09/img_0780.png" alt="Null profile" width="275" height="412" /> <img src="http://happytesting.files.wordpress.com/2010/09/img_0831.png" alt="Null profile 2" width="275" height="412" /></p>
<h3>Server issues</h3>
<p><img src="http://happytesting.files.wordpress.com/2010/09/img_0705.png" alt="Tram time app" width="275" height="412" /> <img src="http://happytesting.files.wordpress.com/2010/09/img_0706.jpg" alt="Real tram times" width="569" height="425" /></p>
<p>Very often you need to serve your client app with data from a server.  Having incorrect or inconsistent data creates these kind of issues.  Like when I use this app for showing when the tram leaves my location.  You might expect that the data source is the same for both iphone client  and monitor at the station. But comparing them showed clearly that this  was not the case. Do you see it?</p>
<p>Showing a wordpress site with an embedded picture within the  tweetdeck UI looks more challenging than you might think of. Maybe CSS  issues on the server side?</p>
<p><img src="http://happytesting.files.wordpress.com/2010/09/img_0721.png" alt="Css issue?" /></p>
<h3>Native apps</h3>
<p>If we take a look beyond the 3rd party apps from app store, I also  want to highlight some native apps. I have actually no clue why my alarm  time disappears sometimes, but it does quite often. It could be noted  that it has nothing to do with the modules that carry out screenshots.  Gut feeling says that it has something to do with having many alarms in  the list.</p>
<p><img src="http://happytesting.files.wordpress.com/2010/09/img_0404.png" alt="Alarm time issue" width="275" height="412" /> <img src="http://happytesting.files.wordpress.com/2010/09/img_0405.png" alt="Alarm time issue 2" width="275" height="412" /></p>
<p>Also App store reveals that there are humans behind all this. Not  thinking of the text length when listing the ”Top paid iPhone apps” is  of course not a very serious bug, but there is a lot of trust to be lost  from sceptical customers that are just about to open their wallet for  getting their first paid app.</p>
<p><img src="http://happytesting.files.wordpress.com/2010/09/img_0873.png" alt="App store string" width="275" height="412" /></p>
<p>So with a background of a software tester, I would like to state that  testing iPhone/iPad software is no different than testing other  software. Take into account that my most recent experiences come from  testing large enterprise systems integrated with each others. Software  is software, and it is programmed by humans.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/09/21/iphone-app-testing-and-bugs/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Future Cocoa Operation</title>
		<link>http://blog.jayway.com/2010/08/19/future-cocoa-operation/</link>
		<comments>http://blog.jayway.com/2010/08/19/future-cocoa-operation/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 17:51:30 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@implementation CalculatorTest

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

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

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

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

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

@interface Calculator : NSObject {

}

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

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

@implementation Calculator

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

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

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

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

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

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

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

		<guid isPermaLink="false">http://blog.jayway.com/?p=2920</guid>
		<description><![CDATA[It has been little more than 2 years since the iPhone was first announced and during that time it has managed to make a huge impact on the mobileindustry. Introduction Just recently, iPhone sales figures surpassed all windows mobile phones combined and in several markets the iPhone has been a top selling phone model. Together [...]]]></description>
			<content:encoded><![CDATA[<p><strong>It has been little more than 2 years since the iPhone was first announced and during that time it has managed to make a huge impact on the mobileindustry. </strong></p>
<h2>Introduction</h2>
<p>Just recently, iPhone sales figures surpassed all windows mobile phones combined and in several markets the iPhone has been a top selling phone model. Together with the launch of App Store, Apple has managed to create a service delivery platform that attracts not only the hardcore users, but also the average Joe. A testament to this is the fact that App Store has had over one billion application downloads with over 50 000 applications available. This large potential customer base, combined with the advantage of having virtually no device fragmentation, makes it quite an attractive platform for mobile application developers. The business model is also lucrative, with Apple offering 70% of revenues from the store to instantly go to the seller of the app without having to pay for distribution or anything else than a one time fee. In this regard, the iPhone has certainly helped Apple put the Objective-C language in the limelight. </p>
<p>For the developer, the transition from higher level languages such as Java may<br />
not be so simple as Objective-C has quite a unique syntax. The goal of this<br />
article is to remedy that by going through the main concepts of Objective-C<br />
from a Java perspective. Hopefully this will help you to get a quicker start in your<br />
iPhone development. You should however be aware that it is equally important<br />
to understand how to use the iPhone’s application frameworks in order to create<br />
applications, this article only scratches the surface of the language you will use. </p>
<h3>Objective-C from a Java perspective </h3>
<p>If you are used to both working in C/C++ and Java you might soon recognize<br />
Objective-C as a middle-ground language, meaning that it provides lower-level<br />
mechanisms than Java while being a more manageable and higher-level language<br />
than C/C++. The language is a strict superset of C, which means it’s possible<br />
to write and compile normal C code using the Objective-C compiler. We also<br />
use pointers (signified in code with an asterisk, *) to objects and not references,<br />
like in Java. For object orientation Objective-C uses a syntax similar to that of<br />
Smalltalk, which might take a little time to get used to if you haven’t seen it<br />
before. Objective-C is a highly dynamic language, much like Ruby and Python,<br />
where it’s possible to change the behavior at runtime. The compiler is quite<br />
forgiving and before getting used to this you will likely discover more problems<br />
during runtime than when using Java. </p>
<p>While some of the features in Objective-C are unique, many of them are<br />
similar to those of Java only named differently. In order to ease the transition,<br />
we will use Java terminology as much as possible and step by step build up a<br />
small example in Objective-C that covers the basic features. In some cases the<br />
examples will keep code from previous examples and in some only the change<br />
will be presented to save space. Regardless, the new code is always in bold font.<br />
Let’s get started. </p>
<h3>Classes </h3>
<p>Unlike Java which uses a single .java file, Objective-C separates class declaration<br />
and definition into two files: .h and .m. The .h file is called the interface, which<br />
shouldn’t be confused with Java interfaces (more on this later). Most importantly,<br />
the interface file lists the methods and member variables that the class contains.<br />
A minimal compilable .h file would look like this: </p>
<pre>@interface MyClass {
}
@end</pre>
<p>This piece of code simply declares an empty interface named MyClass which<br />
you preferably should put in a file named “MyClass.h”. The space between the<br />
“{}” signs is where we will put our member variable declarations and the space<br />
right before the @end tag is where method declarations go. The .m file looks like<br />
this: </p>
<pre>#import ”MyClass.h”
@implementation MyClass
@end</pre>
<p>It’s between the lines starting with @implementation and @end that we will<br />
put our actual method implementations. Notice that there are no “{}” signs<br />
since member variables are declared in the interface file. This minimal example<br />
obviously doesn’t do much but it will compile and it it gives us something to<br />
start with. </p>
<p>Similarly to Java, Objective-C has a superclass that most classes inherit from:<br />
NSObject. But while we in Java are used to an implicit inheritance from this<br />
class, we must here explicitly declare this in our .h files. To inherit a class, we<br />
simply add a colon after the class name in our .h file followed by the name of<br />
the class we wish to inherit:  </p>
<pre>@interface MyClass : NSObject {
} </pre>
<p>Conceptually, NSObject has similarities to java.lang.Object. But it is also more<br />
powerful in the sense that it provides some features that are only possible with the<br />
reflection API in Java. As an example, NSObject allows you to take advantage of the<br />
runtime and determine which methods are implemented. It also contains methods<br />
that are needed for proper memory management such as retain and release which<br />
we will look closer at later on.</p>
<h3>Naming conventions</h3>
<p>Objective-C does not provide any type of namespace functionality like Java does<br />
with packages. Instead, to avoid name clashes, the best way is to use prefixes.<br />
You will see this used heavily throughout the official APIs. NSString (a Foundation<br />
class) and UITextField (of the UIKit framework) are two examples. This makes<br />
it easy to see which classes are written by Apple. We recommend that you use<br />
an abbreviation of your company as two upper case characters and prefix your<br />
classes with that. If your company name is Acme, you could use AC as a prefix. </p>
<p>When programming in Objective-C it is advisable to follow the guidelines from<br />
Apple about naming classes, methods and other building blocks. Typically we<br />
want naming to be very expressive and also highly consistent. This contrasts<br />
Java where, for example, some collection classes use addElement(...) and<br />
sometimes add(...) to add new objects. Consistency makes it a lot easier to<br />
learn the frameworks because they follow the same conventions. We also want<br />
to be expressive and really explain in naming what the class or method does.<br />
Java enforces conventions through JavaBeans standards, but Apple goes far<br />
beyond that. For example, ACPeopleTableViewController would be a suitable<br />
name for a Controller (MVC pattern) class that controls a TableView (standard<br />
component) which contains People. When it comes to methods getters should<br />
not be prefixed by “get” but rather have similar name as the property they are<br />
fetching. If there is a property called defaultColor then the method to get it<br />
is called -(NSColor*)color; not getColor();. There are many other naming<br />
conventions and you’ll rather quickly get used to the standard ones. </p>
<h3>Access Control</h3>
<p>There are three types of access control you can set on your member variables:<br />
private, protected, and public. They have the same effect as in Java. The syntax<br />
for doing this is a bit different tough. Let’s add two member variables to our<br />
header file and make these private: </p>
<pre>@interface MyClass
{
    @private
    int firstNumber, secondNumber;
}
@end </pre>
<p>We simply use the compiler directive “@private” and everything beneath it will<br />
be private until either a “}” or another directive is found. </p>
<p>So how do I make my instance methods private? The answer is that you don’t<br />
have to worry about that, since the language doesn’t formally support changing<br />
the access type on methods. All methods are public!</p>
<h3>Methods</h3>
<p>The equivalent of calling methods in Java is defined as sending messages in<br />
Objective-C. This is one of the big differences between the languages. On the<br />
surface it may appear as we are doing the same thing only with different syntax: </p>
<pre>Java:         myObject.doSomething(myParameter);
Objective-C:  [myObject doSomething:myParameter]; </pre>
<p>But there is in fact a big underlying difference. The doSomething method in<br />
the Java example must exist at compile time or the compilation will fail. The<br />
same does not apply in the Objective-C case. The notion of sending a message<br />
to an object implies that we will send something regardless of whether there is<br />
a receiver or not and how the message together with parameters are handled is<br />
determined at runtime. </p>
<p>Now let’s declare a method in our header file that will add two numbers: </p>
<pre>@interface MyClass {
  @private
  int firstNumber, secondNumber;
}
-(int)add:(int)a to:(int)b; </pre>
<p>The syntax may seem confusing at first but the elegance is displayed once the<br />
method is used to pass a message: </p>
<pre>[myObject add:5 to: 2];</pre>
<p>Notice the readability of that method. Instead of guessing or reading<br />
documentation for method signatures we know right away which parameter<br />
goes where. Now lets add the implementation in the .m file: </p>
<pre>-(int)add:(int)a to:(int)b
{
    return b + a;
} </pre>
<h3>Constructors </h3>
<p>Objective-C doesn’t have the same concept of constructors as Java. Instead,<br />
object creation is divided into two parts: allocation and initialization. There is<br />
no special syntax reserved for object creation (i.e. new in Java). The methods<br />
handling this are regular methods and are named alloc and init respectively. The<br />
two calls are usually nested to allocate and initialize an object on a single line: </p>
<pre>MyClass *myObject = [[MyClass alloc] init];</pre>
<p>Notice the star in front of myObject. This is regular C syntax for declaring<br />
a pointer. Now pointers are usually something that Java people like to avoid<br />
since it can be the source of all kinds of troubles. Fortunately, if you stick to<br />
using Objective-C you almost never have to use the star or any dereference<br />
mechanism when actually using the objects. Just keep in mind that it has to be<br />
there in the declaration. </p>
<p>The alloc method is a static method that resides in NSObject and should never<br />
be overridden. It allocates memory and returns a new instance of the receiving<br />
class. The init method on the other hand is an instance method and should be<br />
overwritten. In fact, the default implementation does nothing but return itself.<br />
The simplest form of init implementation usually looks like this: </p>
<pre>- (id)init
 {
     if ((self = [super init])) {
         /* class-specific initialization goes here */
 }
     return self;
 } </pre>
<p>We always call the parent’s init method and make sure we get something back.<br />
Then we execute our initialize code and return self which is the Objective-C<br />
equivalent of Java’s <em>this</em>.</p>
<p>Just like you often have multiple constructors in Java, you will likely have<br />
more than one initializer in your Objective-C class that takes different types of<br />
arguments. According to convention you should start the name of these methods<br />
with “initWith”. Here’s an initializer that takes two numbers as parameters: </p>
<pre>- (id) initWithNumberA:(int)numberA numberB:(int)numberB
 {
     if ((self = [super init])) {
        firstNumber = numberA;
        secondNumber = numberB;
     }
     return self;
 } </pre>
<p>The convention also says that only one initializer should make the call to super.<br />
It is often convenient to do this in the initializer with the most arguments, and<br />
let the other initializers call that one. Let’s change the first initializer so it looks<br />
like this: </p>
<pre>- (id)init
 {
     return [self initWithNumberA:0 numberB:0];
 } </pre>
<h3>Protocols</h3>
<p>Protocols are essentially the same thing as Java interfaces but with added flexibility.<br />
A class is not always required to implement all methods just to conform to the<br />
protocol, some can be marked as optional. Furthermore, a class can conform to a<br />
protocol by just implementing the required methods, even if it hasn’t explicitly<br />
declared that it is implementing it. Let’s create our own protocol to indicate that<br />
the example class can calculate something, and suitably call it Calculator. We<br />
enter the following in a new .h named CalculatorProtocol.h. </p>
<pre>@protocol Calculator
@required
-(int)calculate;
@end </pre>
<p>The protocol declaration is pretty straight forward. The @required attribute<br />
signifies that the method is mandatory to implement. We could also have written<br />
@optional if we don’t want to force an implementation. It’s also possible to mix<br />
required and optional methods. Now to show that our example class conforms<br />
to this protocol we first change the .h file: </p>
<pre>#import ”CalculatorProtocol.h”
@interface MyClass : NSObject <Calculator>
{ ... </pre>
<p>And then we add the implementation of our getCalculation method in the .m<br />
file:</p>
<pre>-(int)calculate
{
    return [self add:firstNumber to:secondNumber];
} </pre>
<h3>Where’s my garbage collector?</h3>
<p>Unlike Java and desktop Objective-C development there is no garbage collector<br />
available when creating applications for the iPhone. The reason for this is to<br />
allow the best possible performance. This means that you will have to clean up<br />
after yourself manually. Fortunately, the NSObject class contains functionality<br />
to make manual memory management easier. Every object whose class inherits<br />
from NSObject contains a so called retain count which is used to indicate how<br />
many other objects that are using or “owning” it. If you own an object, you are<br />
also responsible for releasing it when you are done, at which point the retain<br />
count willl go down. When the retain count reaches 0 the system will assume it’s<br />
safe to deallocate the memory for your object. So when is the object considered<br />
“used”, i.e. when does the retain count go up? First of all, the retain count will<br />
implicitly increase if you you create the object yourself by using a method name<br />
beginning with “alloc”, “new” or contains “copy”. Secondly, you must explicitly<br />
add one to the retain counter by calling the NSObject method “retain” whenever<br />
you wish to take ownership of an object that you receive by other means, i.e. as<br />
a parameter or from a getter method. </p>
<p>To reduce the retain count, or say that you no longer need the object in question,<br />
you use [myObject autorelease] or [myObject release], where autorelease<br />
signifies that the object should release later. To show how this works we add the<br />
following to our example: </p>
<pre>-(void) setName: (NSString*) newName
{
    [newName retain]; // get ownership, increases retain count for newName
    [name release]; // in case name is already set, we don’t need it anymore
    name = newName; // set name to the new value
} </pre>
<p>We need to retain newName in case we are passing the same object that is<br />
currently assigned to name, or it might be deallocated. When releasing name it’s<br />
possible that it’s not set, but it’s fine to call release on a nil object.</p>
<p>There are situations when you want to autorelease objects. For instance, if you<br />
have a method that returns a NSString that is created inside the method: </p>
<pre>//PROBLEMATIC CODE
-(NSString*)formattedName
{
  NSString *formatted = [[NSString alloc] initWithFormat:@”Name: %@”,name];
  [formatted release];
  return formatted;
} </pre>
<p>If you run this code there’ll be problems. The formatted variable will be released<br />
before it’s returned which means that whoever requested the NSString will get<br />
a pointer to a freed object. The solution is to replace release with autorelease.<br />
Objects that are sent autorelease will be added to an autorelease pool. When<br />
the pool is deallocated release is sent to all objects it contains, including our NSString. The pool is created before events and deallocated when the event has<br />
been handled. That way the formatted variable won’t be deallocated right away. </p>
<pre>-(NSString*)formattedName
{
  NSString *formatted = [[NSString alloc] initWithFormat:@”Name: %@”,name];
  [formatted autorelease];
  return formatted;
}
</pre>
<p>All objects that are not created using alloc, new or copy are automatically added<br />
to the current autorelease pool. So if you don’t want to loose those objects you<br />
need to retain them.</p>
<p>Many objects have convenience methods that return autoreleased objects, so<br />
the easiest solution to our problem would be to avoid the alloc and instead use<br />
a convenience method:</p>
<pre>-(NSString*)formattedName
{
  return [NSString stringWithFormat:@”Name: %@”, name];
} </pre>
<p>Manual memory management is usually one of the tougher parts to get used to<br />
when coming from a “friendlier” language such as Java. It is important however<br />
to get a good understanding in this area as it often can be the source of nasty<br />
bugs. </p>
<h3>Conclusions</h3>
<p>That concludes our example and short introduction to Objective-C, the<br />
language you need to master - or at least learn to use - in order to write great<br />
iPhone applications. The syntax and some concepts differ a bit from Java, but<br />
it’s relatively easy to pick up and get started with. There are many other areas<br />
we haven’t even touched upon, such as the frameworks and tools provided by<br />
Apple. Fortunately there’s a wealth of information available online at the iPhone<br />
Dev Center, where you can read API references, download sample code, watch<br />
tutorial guides and videos as well as discuss with other developers. In order to<br />
develop applications for iPhone you need a Mac computer running Mac OS X<br />
and register as a developer (for free) on Apple’s website. Good luck! </p>
<p><em>Christian Hedin<br />
Stefan Li </em></p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/01/introduction-to-iphone-development/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Adding Sorted Inserts to Cocoa Arrays</title>
		<link>http://blog.jayway.com/2009/03/28/adding-sorted-inserts-to-uimutablearray/</link>
		<comments>http://blog.jayway.com/2009/03/28/adding-sorted-inserts-to-uimutablearray/#comments</comments>
		<pubDate>Sat, 28 Mar 2009 22:39:22 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>

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

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

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

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

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

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

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

