<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jayway Team Blog &#187; Fredrik Olsson</title>
	<atom:link href="http://blog.jayway.com/author/fredrikolsson/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Tue, 20 Jul 2010 08:26:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>UIWebView and JavaScript Woes</title>
		<link>http://blog.jayway.com/2010/06/28/uiwebview-and-javascript-woes/</link>
		<comments>http://blog.jayway.com/2010/06/28/uiwebview-and-javascript-woes/#comments</comments>
		<pubDate>Mon, 28 Jun 2010 07:45:57 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

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

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

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

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

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

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

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

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

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

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

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

  // Allot more code here...

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

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

  public void testRemoteResource() {
    assertNotNull(HTTPProvider.getSharedHTTPProvider().inputStreamForURL(TEST_URL));
  }
}</pre>
<p>It also allows us for explicitly override a singleton if our application has special needs, perhaps a more aggressive cache on a low bandwidth mobile data connection, or special implementation on a buggy Java ME platform. But most importantly for the normal case it will not waste time creating the component until it is actually needed, vastly improving the user experience for your mobile users.</p>
<h3>Take Aways</h3>
<p>Do not fear singletons, it is a great way of lazy creations that will greatly improve startup times and memory consumption on mobile applications.</p>
<p>Avoid using interfaces, they are at least twice as slow as classes, and can not have static methods for acquiring the lazy created components.</p>
<p>Do not enforce the singleton pattern, always use singleton by choice. To allow for testing and easy implementation of special cases.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/15/learn-to-stop-worrying-and-love-the-singleton/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Google Translate and iPhone apps</title>
		<link>http://blog.jayway.com/2010/01/11/google-translate-and-iphone-apps/</link>
		<comments>http://blog.jayway.com/2010/01/11/google-translate-and-iphone-apps/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 09:22:17 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[localization]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[web]]></category>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		<guid isPermaLink="false">http://blog.jayway.com/?p=265</guid>
		<description><![CDATA[My first reaction is that it is polished. Very polished. I have used the unofficial SDK for iPhone OS 1.x software, and nearly everything from iPhone OS 1.x has been redesigned. Small changes from renaming, to removal of changes, and addition of complete frameworks. Not only the provided Frameworks are polished even in beta, so [...]]]></description>
			<content:encoded><![CDATA[<p>My first reaction is that it is polished. Very polished. I have used the unofficial SDK for iPhone OS 1.x software, and nearly everything from iPhone OS 1.x has been redesigned. Small changes from renaming, to removal of changes, and addition of complete frameworks.</p>
<p>Not only the provided Frameworks are polished even in beta, so are the tools. Mac OS X 10.5 Leopard, and Xcode 3.1 is required! If you can live with that works perfectly, with zero setup; double click install package and you are done. Several project templates provided as starting points. Only drawback I find is that the Simulator is not an emulator of the actual hardware, eg. it is running 32-bit x86 not ARM, which makes an Java JIT-compiler undebuggable on the Simulator. Good news is that there is transparent on-device debugging, bad news again; it requires the 2.0 beta software on the phone.</p>
<p>My second reaction is that it is complete. The SDK, as well as the underlying system. It truly is the same system as on desktop Macs running on the device. The same kernel, the same Frameworks. Just a bit more restrictive memory, and screen size.</p>
<p>The documentation is impressive, ranging from conceptual books and a wide range of subjects such as as Human Interface Guidelines, Memory Management, introduction to Objective-C for beginners, writing games using Open GL | ES, security, and much more.</p>
<p>It is obvious by looking at the documentation provided that special care has been taken to cater for the needs of developers without previous experience of Cocoa, or Mac OS X development. Two thirds of the documentation is very basic for anyone with more then a few months experience with Cocoa. And the last third is in depths iPhone OS specific. Most of the documentation is also shared between iPhone OS and desktop Mac OS X, my gut feeling is that Apple want to use iPhone as a lure for developers to embrace Cocoa on Mac OS X as well.</p>
<p>Apart from documentation there is also over 4 hours of video tutorials, ranging from basic overview to optimizing OpenGL | ES games. As well as over 40 example projects, including complete applications. Bot the "show a feature" type that Android have in bounty, and "show a solution" that gives a better feel for how an application should be organized.</p>
<p>And organizing an application is important. Just as with Cocoa for Mac OS X, Cocoa Touch for iPhone OS gives the developer allot for free, provided you follow a few guidelines, and best practices. These are however few, and clear, so anyone can get the hang of it in a matter of hours. Cocoa's inherent talkative API:s with descriptive class, method and constant names, encourages developers to both use and follow "good style". A method named applicationDidLaunch is very hard to misinterpret (It is however misspelled as ApplicationDidLaunch in the iPhone OS Development Introduction ).</p>
<p>And my last reaction; it is beta! Interface Integration is not yet included. That means that you will have to create your UI in code, not using the drag-n-drop as shown on the Keynote last thursday. I miss it dearly, but try to tell myself it is a good thing to first learn how it works under the hood . That and a short list of known bugs, is really the only things I can see standing in the way of a 1.0 release.</p>
<p>I have as a tutorial for myself rewritten the URLyBird assignment for my Java Developer certification with the iPhone OS SDK. Minus the remote server it is up and running beautifully in less than 8 hours of coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/03/09/my-first-weekend-with-iphone-sdk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
