<?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; tips</title>
	<atom:link href="http://blog.jayway.com/tag/tips/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Fixing WP7 app not starting after project rename</title>
		<link>http://blog.jayway.com/2011/10/12/fixing-wp7-app-not-starting-after-project-rename/</link>
		<comments>http://blog.jayway.com/2011/10/12/fixing-wp7-app-not-starting-after-project-rename/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 19:43:04 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tricks]]></category>
		<category><![CDATA[windows phone]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10396</guid>
		<description><![CDATA[If your Windows Phone 7 project isn’t starting at all – you’re not even hitting App.xaml.cs, you’ve probably renamed the app project. Fix: Set the startup object on the app project’s properties page In the .csproj file, this corresponds to the SilverlightAppEntry element: &#60;SilverlightAppEntry&#62;PhotoDiary.App&#60;/SilverlightAppEntry&#62; I would call it a bug, that you cannot rename a [...]]]></description>
			<content:encoded><![CDATA[<p>If your Windows Phone 7 project isn’t starting at all – you’re not even hitting App.xaml.cs, you’ve probably renamed the app project.</p>
<p><strong>Fix</strong>: Set the <em>startup object</em> on the app project’s properties page</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/startup_object.jpg" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="startup_object" border="0" alt="startup_object" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/startup_object_thumb.jpg" width="484" height="202" /></a></p>
<p>In the .csproj file, this corresponds to the <em>SilverlightAppEntry </em>element:</p>
<pre class="brush: xml; first-line: 1;">

&lt;SilverlightAppEntry&gt;PhotoDiary.App&lt;/SilverlightAppEntry&gt;

</pre>
<p>I would call it a bug, that you cannot rename a project and have the <em>SilverlightAppEntry</em> update accordingly. But luckily, the work-around is simple. </p>
<p>Have a nice day!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/12/fixing-wp7-app-not-starting-after-project-rename/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Invoke any Method on any Thread</title>
		<link>http://blog.jayway.com/2011/08/08/invoke-any-method-on-any-thread/</link>
		<comments>http://blog.jayway.com/2011/08/08/invoke-any-method-on-any-thread/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 08:03:16 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tutorial]]></category>

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

@implementation CWMainProxy

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

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

		<guid isPermaLink="false">http://blog.jayway.com/?p=9011</guid>
		<description><![CDATA[Why you might ask? A perfectly valid and sane question, let me explain. Right now I’m setting up continuous integration for both an Azure project and an Android project. I’ve covered my struggle with the Azure project in an earlier post. But now it was time to get the Amazon EC2 Windows Server 2008 with [...]]]></description>
			<content:encoded><![CDATA[<p>Why you might ask? A perfectly valid and sane question, let me explain. Right now I’m setting up continuous integration for both an Azure project and an Android project. I’ve covered my struggle with the Azure project in an earlier <a href="http://blog.jayway.com/2011/03/20/configuring-automatic-deployment-of-a-windows-azure-application-using-teamcity/" target="_blank">post</a>. But now it was time to get the Amazon EC2 Windows Server 2008 with TeamCity to build an Android project and publish the resulting apk file to a folder in sync with Dropbox. The problem is that Dropbox will only sync when started in an active desktop session, so if you log out from the server the syncing stops - this was a problem…</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/07/thinking.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="thinking" border="0" alt="thinking" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/07/thinking_thumb.png" width="343" height="275" /></a></p>
<h2>Why am I writing this?</h2>
<p>As always when face with a very specific unusual problem – Internet is your friend. So I could just have left it there and allowed you to find the answer the same way I did. The thing is that the solution to my problem was a mashup of several standalone solutions presented on the web. So my idea is to summarize what I did hoping that it will help anyone facing the same problem.</p>
<h2>What I did</h2>
<p>So here are the steps that I took in order to get everything working. Quite a few steps but I wanted it detailed enough so that anyone could follow.</p>
<ol>
<li>Right click the Dropbox icon in your system tray and select <strong>Preferences</strong> </li>
<li>Deselect <strong>Show desktop notifications</strong> </li>
<li>Deselect <strong>Start Dropbox on system startup</strong> </li>
<li>Download and install <a href="http://www.microsoft.com/download/en/details.aspx?id=17657" target="_blank">Windows Server 2003 Resource Kit Tools</a>. It will warn you about incompatibility, but you can safely ignore this (or at least I did). </li>
<li>Open the Command Console (Run –&gt; cmd). </li>
<li>Enter <strong>sc create DropboxService binPath= C:\Program Files (x86)\Windows Resource Kits\Tools\srvany.exe DisplayName= &quot;Dropbox Service&quot;</strong> </li>
<li>Open RegEdit and navigate to <strong>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DropboxService\</strong> </li>
<li>Create a new key named <strong>Parameters</strong> </li>
<li>Create a string value called <strong>Application</strong> and enter the full path to your Dropbox executable. Typically <strong>C:\Users\****\AppData\Roaming\Dropbox\bin\Dropbox.exe</strong> </li>
<li>Open Services (Start Menu –&gt; Administrative Tools –&gt; Services) </li>
<li>Locate your <strong>Dropbox Service</strong>, right click and select properties. </li>
<li>Set the service to Autostart </li>
<li>Under the <strong>Log on</strong> tab, check <strong>Allow service to interact with desktop</strong>. </li>
<li>Press <strong>Apply</strong> </li>
<li>Start the service </li>
<li>You will get a popup asking for permissions to display the Dropbox configuration - Accept. </li>
<li>Add your user info </li>
</ol>
<p>Done!</p>
<h2>Thoughts…</h2>
<p>Well yes, I realize that this is not how Dropbox was intended to be used. But it surprised me that the only way, at least that I could find, was to hack away with toolkits, console applications and the registry. I’m not really counting on that there will be an easier way in the future. So this post is as much for me to remember how I did it, so that I won’t have to figure it out again, as for helping anyone else in a similar situation.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/07/12/running-dropbox-as-a-service-on-windows-server-2008/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Chaos Monkey is your friend</title>
		<link>http://blog.jayway.com/2011/05/24/chaos-monkey-is-your-friend/</link>
		<comments>http://blog.jayway.com/2011/05/24/chaos-monkey-is-your-friend/#comments</comments>
		<pubDate>Tue, 24 May 2011 19:47:00 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8503</guid>
		<description><![CDATA[The chaos monkey, a mythical creature. I had actually never heard of it until I read Jeff Atwood’s post (which is excellent and you should read it). Then I realized that I’ve worked with and fought against chaos monkeys my entire career. Tough love sometimes, but the monkey always pushed the software to become more [...]]]></description>
			<content:encoded><![CDATA[<p>The chaos monkey, a mythical creature. I had actually never heard of it until I read <a href="http://www.codinghorror.com/blog/2011/04/working-with-the-chaos-monkey.html">Jeff Atwood’s post</a> (which is excellent and you should read it). Then I realized that I’ve worked with and fought against chaos monkeys my entire career. Tough love sometimes, but the monkey always pushed the software to become more robust each and every time it struck.</p>
<h2>So what is a Chaos Monkey?</h2>
<p>Before I continue, we should perhaps clarify what a chaos monkey is. I think that it all started 1983 during the development of MacPaint and MacPrint (the full story can be found <a href="http://www.folklore.org/StoryView.py?project=Macintosh&amp;story=Monkey_Lives.txt" target="_blank">here</a>). What basically happened was that Steve Capps created a helper application that fed events to the other applications under development. The events represented things such as the keyboard being pressed and mouse clicks. While the application was running it kind of looked like a really frantic monkey was slapping the keyboard and playing with the mouse. Hence, it was named “The Monkey”.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/monkey.jpg" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="monkey" border="0" alt="monkey" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/monkey_thumb.jpg" width="244" height="190" /></a></p>
<p>The monkey was then used to test the applications and make sure that it did not crash whatever you threw at it. Much like when you sit down next to user that tries out your application for the first time and you know… he/she “uses it wrong” so that it provokes a crash. You could argue that it’s their own fault, but deep inside, you know that you probably should have handled those characters in the number field a little better. (Authors note: Neither I nor Jayway as a company compare end users to monkeys, this was just an example…)<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/rambo.jpg" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="rambo" border="0" alt="rambo" align="right" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/rambo_thumb.jpg" width="212" height="297" /></a></p>
<p>Now, fast forward a couple of years and we have Netflix that started move onto Amazon Web Services (you can read more about their experience <a href="http://techblog.netflix.com/2010/12/5-lessons-weve-learned-using-aws.html" target="_blank">here</a>). One of their tasks was to build a robust system that should be able to handle any unexpected problems, Rambo style (yes, they actually called it their “Rambo Architecture”). Unexpected problems typically includes servers going down or processes getting killed.</p>
<p>In order to build this resilient system, Netflix created a service that had as its sole task to randomly attack and kill other services and processes. The service was called the Chaos Monkey. Since the Netflix servers was now under constant attack it forced them to build robust and resilient services that could cope with the unleashed monkey. To prove the worth of the Chaos Monkey, Jeff mentions that</p>
<blockquote><p><a href="http://www.zdnet.com/blog/btl/amazons-web-services-outage-end-of-cloud-innocence/47731">AWS had a huge multi-day outage last week</a>, which took several major websites down, along with a constellation of smaller sites.</p>
<p>Notably absent from that list of affected AWS sites? Netflix.</p>
</blockquote>
<p>I guess the monkey did its job, eh?</p>
<h2>How does it work?</h2>
<p>I think that a good metaphor for the monkey is a vaccine. A vaccine is defined as</p>
<blockquote><p>Any preparation used as a preventive inoculation to confer immunity against a specific disease, usually employing an innocuous form of the disease agent, as killed or weakened bacteria or viruses, to stimulate antibody production.</p>
</blockquote>
<p>Well that kind of sounds the same as our monkey, doesn’t it? We introduce a disease into our system in order to prepare it for the real thing. The disease agent in our case is the monkey and the antibodies is our own code written to cope with unstable system. Our role as developers suddenly become the same as our own bodies immune system. We find and protect all the weak spots in our system and when we are faced with the real deal we are prepared. Neat.</p>
<h2>My very own monkey</h2>
<p>I’m currently working with a project where we, some time ago, involuntary faced our own monkey. Our system is connected with several services and different hardware, such as barcode scanners, printers and card readers. All of which has a tendency to go offline or jam when you least expect it. Especially the printer, a device which reliability has generally not improved since Windows 95, gave us problems in the beginning.</p>
<p>It would stop working when you least expected it and it would certainly not inform anyone that it was now useless. Since we couldn’t figure out the root cause right away we started to implement a robust system that would verify that the printer was operational at, and before, critical moments and then inform the user in a friendly way (instead of just crashing or refusing to print). When we finally found and fixed the root cause of the problem we were well prepared for failures that we could not control, such as paper jam.</p>
<p>If the printer wouldn’t have failed so frequently in the beginning we never would have spent the effort to inoculate our system against it. Now, since the printer disease is gone we have an immune system that can cope with any unsuspected printer failures.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/monkey2.jpg" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="monkey2" border="0" alt="monkey2" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/monkey2_thumb.jpg" width="244" height="244" /></a></p>
<p>Important to note is that we, compared to the Netflix team, didn’t implement our own chaos monkey, we got one without asking for it. When we wrote the code to make our system more resilient, if anyone would have asked us if we where glad for the faulty printer we would most definitively say no. But now we’re reaping the harvest from our hard work and it would not be possible without the help of our very own little chaos monkey.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/05/24/chaos-monkey-is-your-friend/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Lazy&lt;T&gt; with implicit cast to T can give you some pretty code</title>
		<link>http://blog.jayway.com/2010/08/09/lazy-t-with-implicit-cast-to-t/</link>
		<comments>http://blog.jayway.com/2010/08/09/lazy-t-with-implicit-cast-to-t/#comments</comments>
		<pubDate>Mon, 09 Aug 2010 20:01:00 +0000</pubDate>
		<dc:creator>Magnus Mårtensson</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/2010/08/05/lazy-t-with-implicit-cast-to-t/</guid>
		<description><![CDATA[Adding an implicit cast functionality to Lazy&#60;T&#62; can give you an option to writing null checkers in your delayed instantiation properties. The problem Today in our project a colleague was cussing over the fact that he kept writing the same block of code over and over again when null checking a property with a backing [...]]]></description>
			<content:encoded><![CDATA[<p>Adding an implicit cast functionality to <a href="http://msdn.microsoft.com/en-us/library/dd642331.aspx">Lazy&lt;T&gt;</a> can give you an option to writing null checkers in your delayed instantiation properties.</p>
<h3>The problem</h3>
<p>Today in our project a colleague was cussing over the fact that he kept writing the same block of code over and over again when null checking a property with a backing field.</p>
<p>Given the class <span style="color: #2b91af">Foo</span>:</p>
<pre class="code"><span style="color: blue">private </span><span style="color: #2b91af">Foo </span>oldFooProp;
<span style="color: blue">public </span><span style="color: #2b91af">Foo </span>OldFooProp
{
    <span style="color: blue">get
    </span>{
        <span style="color: blue">if </span>(oldFooProp == <span style="color: blue">null</span>)
        {
            oldFooProp = <span style="color: blue">new </span><span style="color: #2b91af">Foo</span>();
        }
        <span style="color: blue">return </span>oldFooProp;
    }
}</pre>
<p>Have any of you written something like this before? It’s a bunch of lines of code that you tend to write (in small variations) over and over again. Sure you can compact it a little but it in the order of 5 – 10 lines of annoying repetitive code.</p>
<p>Some use the <a href="http://msdn.microsoft.com/en-us/library/ms173224.aspx">null coalescing operator (??)</a> version that looks like this:</p>
<pre class="code"><span style="color: blue">public </span><span style="color: #2b91af">Foo </span>OldAlternativeFooProp
{
    <span style="color: blue">get
    </span>{
        <span style="color: blue">return </span>oldFooProp ?? (oldFooProp = <span style="color: blue">new </span><span style="color: #2b91af">Foo</span>());
    }
}</pre>
<p>This version is a little easier to compact down to even a single line.</p>
<p>But we (my colleague and I) can do you one better:</p>
<h3>Here is an optional approach</h3>
<pre class="code"><span style="color: blue">private </span><span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">Foo</span>&gt; foo = <span style="color: blue">new </span><span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">Foo</span>&gt;();

<span style="color: blue">public </span><span style="color: #2b91af">Foo </span>Foo
{
    <span style="color: blue">get
    </span>{
        <span style="color: blue">return </span>foo;
    }
}</pre>
<p>Actually I’d prefer to do that like this but then you have to know the solution below and be comfortable with it:</p>
<p><span style="color: blue">public readonly </span><span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">Foo</span>&gt; Foo = <span style="color: blue">new </span><span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">Foo</span>&gt;();</p>
<p>But wait a minute: That doesn’t work you say, right? You can’t return a <span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">Foo</span>&gt; as a <span style="color: #2b91af">Foo</span> you have to write theFoo.Value.</p>
<h3>The Trick</h3>
<p>The secret trick is to inherit Lazy&lt;T&gt; and implement an <a href="http://msdn.microsoft.com/en-us/library/z5z9kes2%28VS.71%29.aspx">implicit operator</a> for T on it!</p>
<pre class="code"><span style="color: blue">namespace </span>Jayway.com.Sys
{
    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">A version of </span><span style="color: gray">&lt;see cref=&quot;Sys.Lazy{T}&quot;/&gt; </span><span style="color: green">with the twist of being implicitly castable to </span><span style="color: gray">&lt;typeparamref name=&quot;T&quot;/&gt;</span><span style="color: green">.
    </span><span style="color: gray">/// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;T&quot;&gt;</span><span style="color: green">The type of lazy instance we are creating.</span><span style="color: gray">&lt;/typeparam&gt;
    </span><span style="color: blue">public class </span><span style="color: #2b91af">Lazy</span>&lt;T&gt; : System.<span style="color: #2b91af">Lazy</span>&lt;T&gt;
    {
<span style="color: blue">
<pre class="code"><span style="color: green"><font color="#000000">        </font>// Ctors removed for brevity
</span></span><span style="color: blue"><font color="#008000"></font>
        </span><span style="color: gray">/// &lt;summary&gt;
        /// </span><span style="color: green">Cast the </span><span style="color: gray">&lt;see cref=&quot;Lazy{T}&quot;/&gt; </span><span style="color: green">to it's contained </span><span style="color: gray">&lt;typeparamref name=&quot;T&quot;/&gt;
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;lazyT&quot;&gt;</span><span style="color: green">The lazy to cast.</span><span style="color: gray">&lt;/param&gt;
        /// &lt;returns&gt;</span><span style="color: green">The instance of </span><span style="color: gray">&lt;see cref=&quot;Lazy{T}.Value&quot;/&gt;&lt;/returns&gt;
        </span><span style="color: blue">public static implicit operator </span>T(<span style="color: #2b91af">Lazy</span>&lt;T&gt; lazyT)
        {
            <span style="color: blue">return </span>lazyT.Value;
        }
    }
}</pre>
</pre>
<p>Now you can implicitly cast a Lazy&lt;T&gt; to it’s contained type T.</p>
<p>A few alternative constructions for it might look like this:</p>
<pre class="code"><span style="color: blue">public </span>LazyTests()
{
    <span style="color: green">// With parameter
    </span>theFoo = <span style="color: blue">new </span><span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">Foo</span>&gt;(() =&gt; <span style="color: blue">new </span><span style="color: #2b91af">Foo</span>(<span style="color: #a31515">&quot;bar&quot;</span>));

    <span style="color: green">// With <a href="http://martinfowler.com/articles/injection.html">Inversion Of Control</a>
    </span><span style="color: #2b91af">IServiceLocator </span>serviceLocator = GetServiceLocator();
    theFoo = <span style="color: blue">new </span><span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">Foo</span>&gt;(() =&gt; serviceLocator.GetInstance());
}</pre>
<p>I kind of like this code. It’s compact. It’s easy to read. It’s pretty!</p>
<p>Hope you like it too – HTH!</p>
<p>Cheers,</p>
<p>M.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/08/09/lazy-t-with-implicit-cast-to-t/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Handling Lazy + Metadata instances in Managed Extensibility Framework (MEF)</title>
		<link>http://blog.jayway.com/2010/08/04/handling-lazy-metadata-instances-in-managed-extensibility-framework-mef/</link>
		<comments>http://blog.jayway.com/2010/08/04/handling-lazy-metadata-instances-in-managed-extensibility-framework-mef/#comments</comments>
		<pubDate>Wed, 04 Aug 2010 19:25:02 +0000</pubDate>
		<dc:creator>Magnus Mårtensson</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/2010/08/04/handling-lazy-metadata-instances-in-managed-extensibility-framework-mef/</guid>
		<description><![CDATA[Have you ever wanted to dynamically choose from many potential implementations of some code? Would you like to have the power of metadata filtering and lazy instantiation of the selected implementation? Here is how to do just that using Managed Extensibility Framework (MEF) and also a neat trick to handle your implementation/metadata pairs that I [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever wanted to dynamically choose from many potential implementations of some code? Would you like to have the power of metadata filtering and lazy instantiation of the selected implementation? Here is how to do just that using Managed Extensibility Framework (MEF) and also a neat trick to handle your implementation/metadata pairs that I recently put to good use. Code samples and optimizations follow so don’t worry; I won’t remain all theoretical in this post. (<a href="http://msdn.microsoft.com/en-us/library/dd460648.aspx">MEF</a> is part of .NET Framework 4.0 but is available also on CodePlex for other releases – <a href="http://mef.codeplex.com/">MEF Community Site</a>.)</p>
<p>Up front I want to show what I am aiming for so you can evaluate if this is a worth while read: Using the more advanced features of MEF suddenly I find I use these pretty gruesome variable and parameter declarations: <span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">IWorkItem</span>, <span style="color: #2b91af">IWorkItemView</span>&gt;. After applying the fix in this post I am left with the exact same behavior and this much improved declaration: <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">IWork</span>&gt;.</p>
<h3>Background on MEF</h3>
<p>Using MEF you can easily juggle the concept of lazily (using <a href="http://msdn.microsoft.com/en-us/library/dd642331.aspx">System.Lazy&lt;T&gt;</a>) importing an open ended set of instances of a given contract. This is built into the library for you. It takes some getting used to the concept but it is quite powerful. As if this wasn’t enough you can also add metadata to the contracts (with the MEF version of Lazy&lt;T&gt; – <a href="http://msdn.microsoft.com/en-us/library/dd986615%28VS.95%29.aspx">System.Lazy&lt;T, TMetadata&gt;</a>) to enable you to select which of the - potentially many - implementations of the contract that you want to lazily load into your app domain and instantiate. Does this all sound like geek speech? Well it sure is but as I said this is a very powerful concept. Given that you have a good requirement for this scenario you never have to code extensibility code yourself ever again. I would go so far as to say that <strong>MEF makes the extensibility scenario a solved problem!</strong></p>
<h3><strong>My Scenario</strong></h3>
<p>Working with improving the Worker role concept in <a href="http://www.microsoft.com/windowsazure/">Windows AzureI</a> I recently had a use for an open ended set of implementations of what I called “work methods”. I wound up making my work methods implementations of <span style="color: #2b91af">IWorkItem</span>. The metadata I added to my work method classes I decorated with <span style="color: #2b91af">IWorkItemView </span>metadata contract. This is what the two contracts look like:</p>
<pre class="code"><span style="color: blue">public interface </span><span style="color: #2b91af">IWorkItem</span>{
    <span style="color: blue">bool </span>HasWork { <span style="color: blue">get</span>; }
    <span style="color: blue">void </span>DoWork();
}
<span style="color: blue">public interface </span><span style="color: #2b91af">IWorkItemView
</span>{
    <span style="color: blue">string </span>Name { <span style="color: blue">get</span>; }
    <span style="color: blue">int </span>Order { <span style="color: blue">get</span>; }
}</pre>
<p>When using these contracts lazily in MEF I get the ugly instances of <span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">IWorkItem</span>, <span style="color: #2b91af">IWorkItemView</span>&gt;. There is some really cool functionality here for sure but I just can’t bare the ugliness of the statement as I begin to pass these instances around in method calls etc. The cool thing with MEF is that I don’t know beforehand how many implementations I have. All I need to know is that I can get them all:</p>
<pre class="code">[<span style="color: #2b91af">ImportMany</span>]
<span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">IWorkItem</span>, <span style="color: #2b91af">IWorkItemView</span>&gt;&gt; Work { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<p>This gives me a whole enumeration of lazy instances that are combined with the metadata of the metadata contract. On each instance of the lazy works you call .Metadata to access the <span style="color: #2b91af">IWorkItemView</span> contract and .Value to instantiate and return the instance of the <span style="color: #2b91af">IWorkItem</span>. Now I don’t know about you but this is beginning to look kind of hairy to me. After all in my code I am not really concerned with any laziness or metadata contracts. Not only that – provided you are a coder that believes in separation of concerns there is one more issue. To explain the last statement let’s go back to my Windows Azure scenario:</p>
<p>I import my many lazy instances with metadata into my code. Then I’d like to begin to use those instances. I wrote some code to filter out which instance I wanted to use. I wrote code to execute the selected instance. I wanted to separate these two code blocks from each other and I also wanted to be able to exchange filtering methods on the fly. I could continue but some of you have certainly begun to see the problem here. I was now passing around parameters of type <span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">IWorkItem</span>, <span style="color: #2b91af">IWorkItemView</span>&gt;. That’s not exactly pretty! What I found that I was conceptually doing was rather using an instance of something that had the combined contract of my two work-method, and work-metadata contracts:</p>
<pre class="code"><span style="color: blue">public interface </span><span style="color: #2b91af">IWork </span>: <span style="color: #2b91af">IWorkItem</span>, <span style="color: #2b91af">IWorkItemView </span>{ }</pre>
<p>Passing around parameters of type <span style="color: #2b91af">IWork</span> is a lot better than <span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">IWorkItem</span>, <span style="color: #2b91af">IWorkItemView</span>&gt;. You have to all agree to that, right?</p>
<p>So now – finally – the issue becomes that of transforming one instance into the other. I also want to keep the Lazy capability. The transformation technique is mostly built into an abstract base class I’ve written which you can download here:</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F60BB8FA-6F02-4999-8F5E-9DD4E92C4DA7:3e443eaf-0bc2-4650-8cec-1edd01486f4b" class="wlWriterEditableSmartContent">
<div><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/08/MEFContrib.LazyDomainCompactor.zip" target="_self">MEFContrib.LazyDomainCompactor.zip</a></div>
</div>
<p>I have also put the code in the <a href="http://github.com/mefcontrib">MEF Contrib project at Github</a>.</p>
<p>Using the base class comes with a little bit of custom implementation per conversion you want to do from from “lazy with metadata” to “other domain object”. The alternative would have been for me to use a dynamic code generation approach for the implementation but I felt that dynamic code in this instance is a serious overkill. Besides we also need to make sure MEF picks up our implementation which in this case means we have to apply an attribute to our implementation.</p>
<h3>The solution</h3>
<p>To re-iterate: We had the <span style="color: #2b91af">ImportMany </span>statement above which is a bit cumbersome. Instead we are aiming for this:</p>
<p>[<span style="color: #2b91af">Import</span>] </p>
<p><span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">IWork</span>&gt; Work { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</p>
<p>Please notice the two different attributes <span style="color: #2b91af">ImportMany </span>and <span style="color: #2b91af">Import</span>. There is an important difference. The first one will find a lot of implementations of the contract (zero to many) while the latter will find only one exact match to the contract. In the first case we want MEF to find all <span style="color: #2b91af">IWorkItem</span> implementations that are decorated with the <span style="color: #2b91af">IWorkItemView</span> metadata. In the second case we want to find one single collection of <span style="color: #2b91af">IWork</span>.</p>
<p>The trick is to collect all the instances (<span style="color: #2b91af">ImportManyAttribute</span>) and hand them back out (<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.exportattribute.aspx">ExportAttribute</a>) as a single collection. What we do in the base class is import the many lazy with metadata instances and then immediately export a whole collection of the new contract to be picked up somewhere in the code as needed.</p>
<h3>Details</h3>
<pre class="code"><span style="color: blue">public abstract class </span><span style="color: #2b91af">ValueMetadataCompactorBase</span>&lt;TValue, TMetadata, TValueMetadata&gt; :
    <span style="color: #2b91af">IEnumerable</span>&lt;TValueMetadata&gt;
    <span style="color: blue">where </span>TValueMetadata : TValue, TMetadata
{
<span style="color: gray">    </span><span style="color: blue">protected abstract </span>TValueMetadata Compact(<span style="color: #2b91af">Lazy</span>&lt;TValue, TMetadata&gt; lazyValueMetadata);

<span style="color: gray">    </span>[<span style="color: #2b91af">ImportMany</span>(AllowRecomposition = <span style="color: blue">true</span>)]
    <span style="color: blue">internal </span><span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">Lazy</span>&lt;TValueMetadata&gt;&gt; ValueMetadatas { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }

<span style="color: gray">    </span>[<span style="color: #2b91af">ImportMany</span>(AllowRecomposition = <span style="color: blue">true</span>)]
    <span style="color: blue">internal </span><span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">Lazy</span>&lt;TValue, TMetadata&gt;&gt; ValuesWithMetadata { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<pre class="code">     <span style="color: green">// Cliped IEnumerable implementation for brevity [...]
</span>}</pre>
<p>There are a few things to notice here:</p>
<ul>
<li>We <span style="color: #2b91af">ImportMany </span>instances of the <span style="color: #2b91af">Lazy</span>&lt;TValue, TMetadata&gt; and also for good measure we <span style="color: #2b91af">ImportMany </span>istances of <span style="color: #2b91af">Lazy</span>&lt;TValueMetadata&gt;. The reason for the latter is that since we offer the contract <span style="color: #2b91af">IWork </span>for any developer to pick up an implement we can’t be 100% certain some one doesn’t use it in a direct implementation. It is no crime to do so even though the intent is to implement <span style="color: #2b91af">IWorkItem</span> and decorate it with the metadata <span style="color: #2b91af">IWorkItemView</span>. The real reason for not implementing the <span style="color: #2b91af">IWork</span> direct is because we can remain lazy with the metadata if it is real metadata. If we want to start looking at the members of an implementation that does not have metadata we need to load that implementations assembly into the <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.aspx">AppDomain</a>. </li>
<li>The class implements <span style="color: #2b91af">IEnumerable</span>&lt;TValueMetadata&gt;. This is used in the derived classes to <span style="color: #2b91af">Export</span> the behavior and make the transformation accessible to our needy develoeprs. ;~) </li>
</ul>
<p>To use this base class you have to do two things:</p>
<p>1) Implement the base class which constitutes implementing one method for compacting together a TValue and TMetadata into a TValueMetadata.<br />
  <br />2) Apply the <span style="color: #2b91af">ExportAttribute</span> with the parameter <span style="color: blue">typeof</span>(&lt;your type&gt;).</p>
<p>Let me show you my implementation of the compactor for compacting <span style="color: #2b91af">IWorkItem</span>s with <span style="color: #2b91af">IWorkItemView</span> into instances of <span style="color: #2b91af">IWork</span>:</p>
<pre class="code">[<span style="color: #2b91af">Export</span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">IWork</span>&gt;))]
<span style="color: blue">internal class </span><span style="color: #2b91af">WorkCompactor </span>: <span style="color: #2b91af">ValueMetadataCompactorBase</span>&lt;<span style="color: #2b91af">IWorkItem</span>, <span style="color: #2b91af">IWorkItemView</span>, <span style="color: #2b91af">IWork</span>&gt;
{
    <span style="color: blue">protected override </span><span style="color: #2b91af">IWork </span>Compact(<span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">IWorkItem</span>, <span style="color: #2b91af">IWorkItemView</span>&gt; lazyValueMetadata)
    {
        <span style="color: blue">return new </span><span style="color: #2b91af">WorkWrapper</span>(lazyValueMetadata);
    }

    <span style="color: blue">private class </span><span style="color: #2b91af">WorkWrapper </span>: <span style="color: #2b91af">IWork
    </span>{
        <span style="color: blue">private readonly </span><span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">IWorkItem</span>, <span style="color: #2b91af">IWorkItemView</span>&gt; lazyWorkWithMetadata;

        <span style="color: blue">public </span>WorkWrapper(<span style="color: #2b91af">Lazy</span>&lt;<span style="color: #2b91af">IWorkItem</span>, <span style="color: #2b91af">IWorkItemView</span>&gt; lazyWorkWithMetadata)
        {
            <span style="color: blue">this</span>.lazyWorkWithMetadata = lazyWorkWithMetadata;
        }

        <span style="color: blue">public bool </span>HasWork
        {
            <span style="color: blue">get </span>{ <span style="color: blue">return </span>lazyWorkWithMetadata.Value.HasWork; }
        }

        <span style="color: blue">public void </span>DoWork()
        {
            lazyWorkWithMetadata.Value.DoWork();
        }

        <span style="color: blue">public int </span>Order
        {
            <span style="color: blue">get </span>{ <span style="color: blue">return </span>lazyWorkWithMetadata.Metadata.Order; }
        }

        <span style="color: blue">public string </span>Name
        {
            <span style="color: blue">get </span>{ <span style="color: blue">return </span>lazyWorkWithMetadata.Metadata.Name; }
        }
    }
}</pre>
<p>Notice:</p>
<ul>
<li>The annoyance here is that I have to custom implement a boring <span style="color: #2b91af">IWork </span>wrapper ourselves since I am not using a dynamic code approach. </li>
<li>The implementation of said <span style="color: #2b91af">IWork </span>retains the lazy behavior in my implementation since I only forward calls to the members to the contained lazy instance. </li>
<li>The [<span style="color: #2b91af">Export</span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">IWork</span>&gt;))] attribute on the implementation is that which makes my <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">IWork</span>&gt; available to the rest of my code through MEF. </li>
<li>The implementation is marked as <span style="color: blue">internal</span>. MEF doesn’t care – it finds <span style="color: blue">internal</span>, <span style="color: blue">protected</span> and <span style="color: blue">private</span> implementations as well as <span style="color: blue">public</span>.. This means that user coders do not even know that this conversion exists. All the handling of lazy etc. is removed from the “subscribing” code. </li>
</ul>
<h3>Summary</h3>
<p><strong>Note to self:</strong> Write less epic blog posts. ;~)</p>
<p>I hope this post gives you some insight into how MEF works as well as a neat trick to simplify some of your MEF-Import code and lazy-metadata craziness. The functionality is very good to have but I really do not want library specific concerns to affect my code too much. Do you?</p>
<p>Cheers,</p>
<p>M. (the NoOpMan)</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/08/04/handling-lazy-metadata-instances-in-managed-extensibility-framework-mef/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Performing any Selector on the Main Thread</title>
		<link>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/</link>
		<comments>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 14:57:48 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[cocoa touch]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tutorial]]></category>

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

