Archive for the ‘Threading’ Category

Part II: Spawning Threads Using Selectors With Multiple Parameters

05/18/2010 9 comments

In Part I, we introduced a method that emulates the Apple-supplied convenience method performSelectorInBackground:withObject:, but which adds support for selectors that take multiple objects as arguments. We saw the power of NSInvocation objects, but also saw how they were a bit cumbersome to use on a routine basis. Our solution gave us what we wanted by allowing us to pass in an array of objects to be used, along with a multi-parameter selector, to invoke an arbitrary method on a background thread (or on the main thread).

This solution is a great step forward when we need to invoke something like [myObj setCharacter:@"The Doctor" currentActor:@"Matt Smith"]. But what if we have a bunch of methods that don’t take objects? Wrapping them all in NSValues begins to really litter-up the code, and is frankly a bit tedious. And what if one want to invoke something like [myObj setCharacter:@"The Doctor" favoriteActors:@"Tom Baker", @"David Tennant", @"Matt Smith"]? There has to be a cleaner way, right? Behold! There is, and the answer lies in the somewhat obscure-ish va_arg macro. Now we can save the world from our unwieldy code. Allons-y!

Read more…

Part I: Spawning Threads Using Selectors With Multiple Parameters

07/07/2009 3 comments

If you’ve spent much time working with thread in Cocoa, you have likely come across the following roadblock: you can only specify one parameter when spawning a new thread from a selector.  The first reaction is to rewrite your method with a single parameter that takes collection of objects and then unpacks them.  This can lead to untidy or prolix code, though, and doesn’t do anything for readability or debug-ability. You also need to know when you define your method that you will want to spawn it off–otherwise you face refactoring down the road.  At any rate, spawning via selector is a convenience method; we shouldn’t be forced to change our code in order to use it.

You can see glimmers of hope, though, as you study the problem.  Objective-C allows you to include multiple parameters in a selector, as in @selector(myMethod:withAValue:andAnother:). However, you will throw an exception at runtime since you can only specify one context object, and thus, the runtime will only have values to pass for one of the arguments. So close, and yet, so far away.  Is our only other option subclassing NSThread?  Thankfully, no.  We can have our cake and eat it, too, with just a little work on our part. The answer lies in the NSInvocation class.
Read more…