<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Jayway Team Blog » Frameworks</title>
	
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<pubDate>Wed, 18 Mar 2009 10:13:15 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/jayway/posts/frameworks" /><feedburner:info uri="jayway/posts/frameworks" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Hidden methods in Sony Ericsson Java Platform</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/frameworks/~3/DBKOXppdusk/</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[Frameworks]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[mobile]]></category>

		<category><![CDATA[tips]]></category>

		<category><![CDATA[tricks]]></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 History
We [...]]]></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>
<img src="http://feeds.feedburner.com/~r/jayway/posts/frameworks/~4/DBKOXppdusk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/09/hidden-methods-in-sony-ericsson-java-platform/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2009/03/09/hidden-methods-in-sony-ericsson-java-platform/</feedburner:origLink></item>
		<item>
		<title>Proxy Based AOP for Cocoa Touch</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/frameworks/~3/5u937TTStAE/</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[Frameworks]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[aop]]></category>

		<category><![CDATA[iphone]]></category>

		<category><![CDATA[objective-c]]></category>

		<category><![CDATA[proxy]]></category>

		<category><![CDATA[reflection]]></category>

		<category><![CDATA[tips]]></category>

		<category><![CDATA[tricks]]></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>
<img src="http://feeds.feedburner.com/~r/jayway/posts/frameworks/~4/5u937TTStAE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/06/proxy-based-aop-for-cocoa-touch/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2009/03/06/proxy-based-aop-for-cocoa-touch/</feedburner:origLink></item>
		<item>
		<title>Finding Subview of a Particular Class in Cocoa</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/frameworks/~3/WKUU7SNDf6k/</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[Frameworks]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[iphone]]></category>

		<category><![CDATA[mobile]]></category>

		<category><![CDATA[objective-c]]></category>

		<category><![CDATA[tips]]></category>

		<category><![CDATA[tricks]]></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 when [...]]]></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>
<img src="http://feeds.feedburner.com/~r/jayway/posts/frameworks/~4/WKUU7SNDf6k" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/02/24/finding-subview-of-a-particular-class-in-cocoa/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2009/02/24/finding-subview-of-a-particular-class-in-cocoa/</feedburner:origLink></item>
		<item>
		<title>Devoxx highlights</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/frameworks/~3/bAG5TvkJoHQ/</link>
		<comments>http://blog.jayway.com/2008/12/23/devoxx-highlights/#comments</comments>
		<pubDate>Tue, 23 Dec 2008 22:29:31 +0000</pubDate>
		<dc:creator>Jacob Mattsson</dc:creator>
		
		<category><![CDATA[Agile]]></category>

		<category><![CDATA[Events]]></category>

		<category><![CDATA[Frameworks]]></category>

		<category><![CDATA[Spring]]></category>

		<category><![CDATA[bdd]]></category>

		<category><![CDATA[concurrency]]></category>

		<category><![CDATA[conference]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[spring dm]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=699</guid>
		<description><![CDATA[In order to embrace the true Christmas spirit, I thought I'd share a few goodies from the Devoxx conference that took place in Antwerp, Belgium in mid December. Devoxx is the former JavaPolis that has changed name due to trademarking issues with Sun. Nonetheless, it's still the worlds largest independent Java conference, where the 3200 [...]]]></description>
			<content:encoded><![CDATA[<p>In order to embrace the true Christmas spirit, I thought I'd share a few goodies from the <a href="http://devoxx.com">Devoxx conference</a> that took place in Antwerp, Belgium in mid December. Devoxx is the former JavaPolis that has changed name due to trademarking issues with Sun. Nonetheless, it's still the worlds largest <em>independent</em> Java conference, where the 3200 attendees find themselves being literally showered with news from the broad Java community. Below follow summaries from some of the, IMHO, best sessions from this years conference. Enjoy!</p>
<h3>BDD in Java with easyb (John Ferguson Smart)</h3>
<p>John started out by arguing that TDD is not about testing, it's about writing better code. That is, it's about making your code more maintainable, flexible, reliable and simple. TDD is forces the programmer to think about how to test the class before actually writing the class. BDD, on the other hand, helps to determine what to test and to write more focused code, by starting with the behavior. Instead of thinking that you're testing your class, you should think that you're validating your requirements! </p>
<p>easyb is a BDD testing framework for Java, written in Groovy (hence providing full access to all Java API's). It ensures that tests become clearer and easier to both write and read!  It helps the developer to focus on the requirements only. A competitor to easyb is JBehave, which is an extension to JUnit. However, according to John, JBehave is more cumbersome than easyb.</p>
<p>easyb makes use of stories, much like the story cards in the Agile world. In a story, a narrative approach is used to describe a precise requirement. In easyb, a story could look like this:</p>
<pre class="groovy">&nbsp;
scenario “Make initial deposit onto a <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> account”, <span style="color: #66cc66;">&#123;</span>
	given “a <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> account”
	when “an initial deposit is made”
	then “the balance should be equal to the amount deposited”
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>This scenario is quite clear and readable, isn't it!? Furthermore, it's self-documenting - a very appreciated feature =) And the syntax is so trivial that even a non-technical stakeholder would have no problem understanding it. The developer can then reuse the given scenario (pseudo) code and implement the test case, like this:</p>
<pre class="groovy">&nbsp;
<span style="color: #a1a100;">import com.mycompany.bankonline.domain.Account</span>
&nbsp;
scenario “Make initial deposit onto a <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> account”, <span style="color: #66cc66;">&#123;</span>
	given “a <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> account”, <span style="color: #66cc66;">&#123;</span>
		account = <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> Account<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
	<span style="color: #66cc66;">&#125;</span>
	when “an initial deposit is made”, <span style="color: #66cc66;">&#123;</span>
		initialAmount = <span style="color: #cc66cc;">100</span>
		account.<span style="color: #006600;">makeDeposit</span><span style="color: #66cc66;">&#40;</span>initialAmount<span style="color: #66cc66;">&#41;</span>
	<span style="color: #66cc66;">&#125;</span>
	then “the balance should be equal to the amount deposited”, <span style="color: #66cc66;">&#123;</span>
		account.<span style="color: #006600;">balance</span>.<span style="color: #006600;">shouldBe</span> initialAmount
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The <code>shouldBe</code> call is an intuitive and readable way to verify that the requirement holds. Another way to verify the outcomes is to use the <code>ensure</code> syntax. Example:</p>
<pre class="groovy">&nbsp;
ensure<span style="color: #66cc66;">&#40;</span>account.<span style="color: #006600;">balance</span> &gt; <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>
&nbsp;</pre>
<p>or</p>
<pre class="groovy">&nbsp;
ensure<span style="color: #66cc66;">&#40;</span>account<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	has<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>balance:<span style="color: #cc66cc;">100</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>easyb could be extended to use DBUnit (and further plugins for Grails and Excel are on the way). On the IDE support, the only good option is IntelliJ IDEA. It really comes down to the Groovy support, and Eclipse and NetBeans doesn't shine here. In those cases, you're better off running the tests in Maven or Ant, which both are well supported. In the upcoming version, easyb will have full support for Continuous Integration (CI), enabling automatic test execution in a CI-server such as Hudson.</p>
<p>Furthermore, easyb comes with a web application - Easiness (cmp. Fitnesse) - where stakeholders can create stories in plain text. The developers can then go ahead and implement the stories defined by the stakeholders. This is an important features, that further improves the cooperation between the customer and the provider. It really seems like a quite nice little framework! If you agree, have a look at it at <a href="http://easyb.org/">http://easyb.org/</a>.</p>
<h3>From Concurrent to Parallel – Library-based parallelism in JDK 7 (Brian Goetz)</h3>
<p>Brian is an expert in the concurrency area, but he's not a good presenter! He speaks faster than I can read, and his slides are so packed with info that he doesn't have time to say the half of it. That put aside, in this very interesting session Brian presented some really cool concurrency features to be included in JDK 7.</p>
<p>As you probably know, JDK 5 introduced a set of very useful classes for course-grained parallelism. JDK 7 will introduce a framework for fine-grained parallelism - the "fork-join" framework.</p>
<p>We have now reach a point in time when Moore's laws isn't valid anymore. The new reality is not faster CPUs but more CPUs. To adapt to these changes, programmers have to change the way they think about parallelism. The unit of work (UoW) that represents a task to be solved must be split into even smaller parts to be able to keep all hardware busy. Nowadays, it isn't enough to for ex. spawn a new thread for each service call in a server, the UoW must be split up even further.</p>
<p>Examples of finer-grained parallelism is searching, sorting and filtering a data set. Such a task is preferably solved by dividing it into sub-problems and combining the sub-results at the end. We could use the course-grained concurrency tools (for ex. <code>Executor</code> + <code>Future</code>) introduced in JDK 5 to solve this problem. However, with multiple CPUs available, these tools doesn't perform optimally. For ex., the shared work queue in the <code>Executor</code> becomes a bottle neck when the number of threads/CPUs increases. Furthermore, these tools provide no form of load balancing, i.e. if one thread finishes before the others, it is never reused.</p>
<p>The divide-and-conquer algorithm could also be applied to solve the problem. This great advantage of this approach is that it's independent of the number of CPUs used! Using plain threads for this approach is too expensive though, since thread creation costs way too much. However, the fork-join-operation in JDK 7 solves problems like these using the divide-and-conquer algorithm in a much more effective way! Internally, it uses an slim thread pool to overcome the cost of thread creation. Furthermore, no data-copying penalty exist since the data set (for ex. an array) is not divided/copied during the solution. Instead, the indexes within the data structure is used to define each data subset. Another advantage is that the code doesn't know how many CPUs it executes on, hence it's portable! </p>
<p>While the <code>Executor</code> (JDK 5) should be used for tasks consisting of both IO and computing, the fork-join-operation (JDK 7) should be used for highly compute-intensive tasks. Examples of such tasks are matrix operations, numerical integrations and game playing. The JDK 7 class to be used for these kind of problems is <code>ParallelArray</code>. It's a utility class that greatly simplifies the work of solving a task in parallel. You can think of it as an in-memory database for data sets. Typical usage is:</p>
<pre class="java">&nbsp;
ParallelLongArray pa = ParallelLongArray.<span style="color: #006600;">createUsingHandoff</span><span style="color: #66cc66;">&#40;</span>array, forkJoinPool<span style="color: #66cc66;">&#41;</span>;
<span style="color: #993333;">long</span> max = pa.<span style="color: #006600;">max</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>The <code>ParallelArray</code> class provides operations for:</p>
<ul>
<li>Filtering (nestable)</li>
<li>Mapping</li>
<li>Replacement</li>
<li>Aggregation (max, count, sum, ...)</li>
<li>Application (one action performed for each selected element)</li>
</ul>
<p>To compare, the <code>ParallelArray</code> class acts much like the Map-Produce concept introduced by Google but it works in a different domain (local system instead of in a distributed system).</p>
<p>The only downside really is that JDK 7 isn't scheduled until mid 2010, meaning we'll have to wait quite some time before we can actually use these new concurrency features. But from the looks of it ... it may be worth the wait!</p>
<h3>The SpringSource DM Server (Joris Kuipers)</h3>
<p>The reasons why SpringSource decided to develop a new application server were many. Today, modularity is important and developers spend much time on achieving it in their applications (layering, separation of concerns, etc.). However, when the application is deployed, all modularity is lost - the deployable unit is one huge, monolithic WAR file. That means that sharing code (let alone services) between applications become hard if not impossible. In order to perform the smallest update on the application, whole WAR file have to be redeployed. Furthermore, the servers themselves lack modularity; they come prepackaged with a lot of modules but there's no way to configure that your application only make use of a couple of them. Hence, they are all left in there, consuming unnecessary CPU cycles and memory.</p>
<p>The DM (Dynamic Modules) server was developed to tackle these issues of non-modularity. In order to achieve true modularity, is has been built on top of OSGi (namely the Equinox container). Since OSGi can be quite hard sometimes, the DM server conceal the complexity of OSGi in the same way as the Spring framework does with for ex. Remoting or JMX. </p>
<p>In order to be able to use a third-party library from within the DM server (and from any other OSGi containers), the standard JAR library needs to be extended with OSGi-specific meta data - the OSGi manifest. SpringSource has therefore created the Enterprise Bundle Repository, where they have started to upload and publish OSGi-ified Java EE libraries. If you're using Maven or Ivy, the bundle repository can easily be configured as a remote (or local) repository.</p>
<p>The DM server also introduces a couple of new OSGi import constructs, enabling ease of development. One example is the "Import-library" that can be useful if you want to make use of a framework (for ex. Spring) but don't want to waste your time having to specify every single Import-package (for example Spring-Remoting) within the framework (as you normally would have had to do). This doesn't affect performance improvement since (thanks to OSGi) none of the pre-installed bundles are loaded before they are actually used! Furthermore, with the DM server it's now possible to remove the library bloat of monolithic Java EE WARs. Instead of building the external libraries into your WAR, you can instead declare them as dependencies in the OSGi manifest headers. The server will then convert these into plain "Import-package" constructs during deployment. That way, the size of the built/deployed WAR can be reduced significantly!</p>
<p>In the DM server, one can of course deploy plain OSGi bundles but also WARs, EARs etc. Typical scenarios for deploying a plain OSGi bundle are stand-alone libraries, global services and small stand-alone applications. However, being able to deploy a bundle is not enough in most cases ... A normal application normally consist of multiple bundles, which becomes hard to un/deploy since there is no single deployable unit. Furthermore, with multiple bundles you don't get a common log file or a notion of an application scope. To tackle this issue, the DM server adds the notion of an application by introducing the PAR (Platform Archive) format. It's basically a JAR with a number of 'Application-*' manifest headers. You can think of it as an EAR in Java EE. PARs are versioned and the versions apply to all of their bundles. This mean that one can deploy a PAR twice with different versions but with the same bundles, without conflicts.</p>
<p>The DM server comes in several versions. Of course there's the community version, using a GPL and SpringSource license. Then there's the commercial license where full support from SpringSource is included. On the extension side, better Maven support will soon be released so that the dependencies can be specified in a single place (not like now when you have to duplicate them in the pom and in the manifest). There's a Eclipse-plugin available that enables re/deployments from within the IDE.</p>
<p>These are some of the features in the DM server. There are plenty or more cool ones, read all about them <a href="http://www.springsource.com/products/suite/dmserver">here</a>. There, you'll also find a lot of sample applications that can get you going! With the DM server, SpringSource feel that they are filling the (up until now) empty space of server side OSGi and states that "The DM server is the healthy new way to run your apps!". I must say it looks very promising! Why don't you go ahead and try it out!? I know I will!</p>
<p><em>If you appreciated these posts, you will definitely enjoy next years conference! Pick up your calendar and reserve December 2009 for a great week at Devoxx!</em></p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/frameworks/~4/bAG5TvkJoHQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/23/devoxx-highlights/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2008/12/23/devoxx-highlights/</feedburner:origLink></item>
		<item>
		<title>UIButton troubles, a better solution</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/frameworks/~3/_pRQCa1Fyjo/</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[Design Patterns]]></category>

		<category><![CDATA[Embedded]]></category>

		<category><![CDATA[Frameworks]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[iphone]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[objective-c]]></category>

		<category><![CDATA[tips]]></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 private [...]]]></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>
<img src="http://feeds.feedburner.com/~r/jayway/posts/frameworks/~4/_pRQCa1Fyjo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/17/uibutton-troubles-a-better-solution/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2008/12/17/uibutton-troubles-a-better-solution/</feedburner:origLink></item>
		<item>
		<title>What’s new in PowerMock 1.1</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/frameworks/~3/WvxyAGFZiEU/</link>
		<comments>http://blog.jayway.com/2008/12/15/whats-new-in-powermock-11/#comments</comments>
		<pubDate>Mon, 15 Dec 2008 08:21:13 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
		
		<category><![CDATA[Frameworks]]></category>

		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[Testing]]></category>

		<category><![CDATA[commons-logging]]></category>

		<category><![CDATA[easymock]]></category>

		<category><![CDATA[jmock]]></category>

		<category><![CDATA[log4j]]></category>

		<category><![CDATA[mockito]]></category>

		<category><![CDATA[powermock]]></category>

		<category><![CDATA[slf4j]]></category>

		<category><![CDATA[testng]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=586</guid>
		<description><![CDATA[We're proud to announce that PowerMock 1.1 was released a couple of days ago and it has many new interesting features. 
Framework independence
First of all the internal structure of the project has undergone major changes. PowerMock core is no longer coupled to EasyMock which means that PowerMock can now be used as a foundation for [...]]]></description>
			<content:encoded><![CDATA[<p>We're proud to announce that <a href="http://www.powermock.org">PowerMock</a> 1.1 was released a couple of days ago and it has many new interesting features. </p>
<h3>Framework independence</h3>
<p>First of all the internal structure of the project has undergone major changes. PowerMock core is no longer coupled to EasyMock which means that PowerMock can now be used as a foundation for testability for other mock frameworks. Our intention is that in the future you pick a combination of a mock extension API of choice (such as EasyMock, Mockito or JMock) and a test framework of choice (such as JUnit or TestNG) to enable increased testability for your code. With the new release PowerMock has some basic support for <a href="http://www.mockito.org">Mockito</a> using the Mockito extension api. This means that you can mock final and static methods, use annotations, enable partial mocking, mocking of signed classes even if they're package private and spying of final classes and methods. Expect more features in the upcoming releases! It's possible to create your own extension API's as well so you can benefit from the PowerMock features in virtually any mock framework.</p>
<h3>Test listeners</h3>
<p>Another noteworthy feature of the new release is the test listener support. This means that you can create listeners and get notifications of various events, such as before a test method is about to execute or the outcome of an executed test method etc. The purpose of these test listeners is to provide a framework-independent way to get and react to these notifications by implementing the <code>org.powermock.core.spi.PowerMockTestListener</code> and pass it to the <code>PowerMockListener</code> annotation. PowerMock has some built-in test listeners for you to use, for example it has an <code>AnnotationEnabler</code> that let's you use annotations to create your mock objects. For example consider the following piece of code:</p>
<pre>
@RunWith(PowerMockRunner.class)
@PowerMockListener(AnnotationEnabler.class)
 public class PersonServiceTest {

 	@Mock
  	private PersonDao personDaoMock;

  	private PersonService classUnderTest;

  	@Before
  	public void setUp() {
  		classUnderTest = new PersonService(personDaoMock);
  	}
   ...
  }
</pre>
<p>Using the <code>@Mock</code> annotation eliminates the need to setup and tear-down mocks manually which minimizes repetitive test code and makes the test more readable. The <code>AnnotationEnabler</code> works for both the EasyMock and Mockito API's. You can also supply the names of the methods that you wish to mock if you want to create a partial mock, for example:</p>
<pre>
@RunWith(PowerMockRunner.class)
@PowerMockListener(AnnotationEnabler.class)
 public class PersonServiceTest {

 	@Mock("getPerson")
  	private PersonDao personDaoMock;

  	private PersonService classUnderTest;

  	@Before
  	public void setUp() {
  		classUnderTest = new PersonService(personDaoMock);
  	}
   ...
  }
</pre>
<p>This piece of code will instruct PowerMock to create a partial mock of the PersonDao where only the "getPerson" method is mocked. Since EasyMock has support for nice and strict mocks you can use the <code>@MockNice</code> and <code>@MockStrict</code> annotations to get the benefits of this.</p>
<h3>Mock policies</h3>
<p>One really cool feature of the 1.1 release is something that we refer to as mock policies. A Mock Policy can be used to make it easier to unit test some code with PowerMock in isolation from a certain framework. A mock policy implementation can for example suppress some methods, suppress static initializers or intercept method calls and change their return value (for example to return a mock object) for a certain framework or set of classes or interfaces. A mock policy can for example be implemented to avoid writing repetitive setup code for your tests. Say that you're using a framework X that in order for you to test it requires that certain methods should always return a mock implementation. Perhaps some static initializers must be suppressed as well. Instead of copying this code between tests it would be a good idea to write a reusable mock policy. </p>
<p>PowerMock 1.1 provides three mock policies out of the box for mocking slf4j, java commons-logging and log4j. Let's pick slf4j as an example and let's say you have a class that looks like this:</p>
<pre>
public class Slf4jUser {
        private static final Logger log = LoggerFactory.getLogger(Slf4jUser.class);

        public final String getMessage() {
                log.debug("getMessage!");
                return "log4j user";
        }
}
</pre>
<p>To stub all calls to the logger you can use the Slf4j mock policy that takes care of doing all necessary setup for you. You use it like this:</p>
<pre>
@RunWith(PowerMockRunner.class)
@MockPolicy(Slf4jMockPolicy.class)
public class Slf4jUserTest {
     ...
}
</pre>
<p>Note that we don't have do any setup at all to mock slf4j, the Slf4jMockPolicy takes care of this.</p>
<p>Mock policies can also be chained or nested like this:</p>
<pre>
@RunWith(PowerMockRunner.class)
@MockPolicy({MockPolicyX.class, MockPolicyY.class})
public class MyTest {
    ...
}
</pre>
<p>You can of course create your own mock policies by implementing the <code>org.powermock.core.spi.PowerMockPolicy</code> interface. For more information on mock policies please have a look at the <a href="http://code.google.com/p/powermock/wiki/MockPolicies">documentation</a>. </p>
<h3>Other</h3>
<p>There are of course many other smaller features and improvements such as the ability to suppress individual fields and better support for resetting mocks in the EasyMock API. You can read about all the new features and bug fixes in the <a href="http://powermock.googlecode.com/svn/trunk/changelog.txt">changelog</a>. Please visit our <a href="http://www.powermock.org">web-page</a> for more information and downloads.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/frameworks/~4/WvxyAGFZiEU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/15/whats-new-in-powermock-11/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2008/12/15/whats-new-in-powermock-11/</feedburner:origLink></item>
		<item>
		<title>UIButton troubles, and Obj-C magic</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/frameworks/~3/ULXxviBGBg8/</link>
		<comments>http://blog.jayway.com/2008/12/12/uibutton-troubles-and-obj-c-magic/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 13:54:56 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
		
		<category><![CDATA[Frameworks]]></category>

		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[iphone]]></category>

		<category><![CDATA[objective-c]]></category>

		<category><![CDATA[tips]]></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 UITableViewCell [...]]]></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>
<img src="http://feeds.feedburner.com/~r/jayway/posts/frameworks/~4/ULXxviBGBg8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/12/uibutton-troubles-and-obj-c-magic/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2008/12/12/uibutton-troubles-and-obj-c-magic/</feedburner:origLink></item>
		<item>
		<title>iPhone Tech Talks - Stockholm</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/frameworks/~3/KV9dFz4qfNs/</link>
		<comments>http://blog.jayway.com/2008/12/09/iphone-tech-talks-stockholm/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 08:03:51 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
		
		<category><![CDATA[Embedded]]></category>

		<category><![CDATA[Events]]></category>

		<category><![CDATA[Frameworks]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Usability]]></category>

		<category><![CDATA[apple]]></category>

		<category><![CDATA[design]]></category>

		<category><![CDATA[iphone]]></category>

		<category><![CDATA[mobile]]></category>

		<category><![CDATA[sdk]]></category>

		<category><![CDATA[tricks]]></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 any [...]]]></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>
<img src="http://feeds.feedburner.com/~r/jayway/posts/frameworks/~4/KV9dFz4qfNs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/09/iphone-tech-talks-stockholm/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2008/12/09/iphone-tech-talks-stockholm/</feedburner:origLink></item>
		<item>
		<title>Accelerometer and Vibration on the iPhone</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/frameworks/~3/YF94CqWx3bo/</link>
		<comments>http://blog.jayway.com/2008/11/25/accelerometer-and-vibration-on-the-iphone/#comments</comments>
		<pubDate>Tue, 25 Nov 2008 06:48:47 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
		
		<category><![CDATA[Embedded]]></category>

		<category><![CDATA[Frameworks]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[accelerometer]]></category>

		<category><![CDATA[android]]></category>

		<category><![CDATA[iphone]]></category>

		<category><![CDATA[objective-c]]></category>

		<category><![CDATA[oredev]]></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 :). ds.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/frameworks/~4/YF94CqWx3bo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/11/25/accelerometer-and-vibration-on-the-iphone/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2008/11/25/accelerometer-and-vibration-on-the-iphone/</feedburner:origLink></item>
		<item>
		<title>PowerMock 0.8 released</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/frameworks/~3/JzDxnuEHSnU/</link>
		<comments>http://blog.jayway.com/2008/10/27/powermock-08-released/#comments</comments>
		<pubDate>Mon, 27 Oct 2008 19:37:33 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
		
		<category><![CDATA[Frameworks]]></category>

		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[Testing]]></category>

		<category><![CDATA[easymock]]></category>

		<category><![CDATA[junit]]></category>

		<category><![CDATA[mock]]></category>

		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=371</guid>
		<description><![CDATA[Previously a colleague of mine described an idea for mocking static methods. Earlier this year we started an open source project to implement these ideas in a very simple to use form. The idea is that it will just be a normal jar file that extends EasyMock and JUnit. Instead of using AspectJ we have [...]]]></description>
			<content:encoded><![CDATA[<p>Previously a colleague of mine described an idea for <a href="http://blog.jayway.com/2007/02/16/static-mock-using-aspectj/">mocking static methods</a>. Earlier this year we started an open source project to implement these ideas in a very simple to use form. The idea is that it will just be a normal jar file that extends EasyMock and JUnit. Instead of using AspectJ we have created our own classloader which means that you don't have to make changes to your build environment. <a href="http://www.powermock.org">PowerMock</a>, as the project is called,  is mostly intended for whitebox unit testing where you know what is going on inside a class or method that you want to test. There is even a class called Whitebox which can be used for simple access to private methods and fields. Besides static mocking we have many other interesting features such as mocking constructors, final classes and methods, private methods, removal of static initializers etc.</p>
<p>We have received some feedback and have also started some evaluation in one of our customer's project. Besides bug-fixes and documentation updates we are starting to stabilize the API and preparing for the 1.0 release. We are also <a href="http://www.oredev.org/topmenu/program/trackjava/johanhalebyjankronqvist.4.3efb083311ac562f9fe80009168.html">presenting PowerMock</a> at this years <a href="http://www.oredev.org/">Øredev</a> conference. You're more than welcome to try it out for yourself.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/frameworks/~4/JzDxnuEHSnU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/10/27/powermock-08-released/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2008/10/27/powermock-08-released/</feedburner:origLink></item>
	</channel>
</rss>
