Filed under Objective-C

Matryoshka Functions

by


The other day, I was working with the Flex function BindingUtil.bindProperty(). I always have a hard time remembering which pair of arguments comes first, the ‘site’ or the ‘host’ and to be honest, the names don’t really make much sense to me. “Oh, if only this were an Objective-C project I would have to laboriously type out each name of each parameter.” I thought, “It would be so much more obvious if it were writen like Bind.property("foo").fromObject(bar).toTheValueOfProperty("foo").ofObject(baz);.”

What followed was the discovery/invention of just such a thing, a nested, super-verbose function. The function achieves this by returning an instance of an internal class with nothing in it except for the next step in the chain.

package
{
	public class Bind
	{
		public static function updateProperty(object:Object, property:String):BindSource {
			return new BindSource(object, property);
		}
	}
}
import mx.binding.utils.BindingUtils;
class BindSource {

	private var targetObject:Object;
	private var targetProperty:String;

	public function BindSource(targetObject:Object, targetProperty:String):void {
		this.targetObject = targetObject;
		this.targetProperty = targetProperty;
	} 

	public function whenSourcePropertyChanges(object:Object, property:String):void {
		BindingUtils.bindProperty(targetObject, targetProperty, object, property);
	}
}

To call this function you would use:

Bind.updateProperty(foo, "bar").whenSourcePropertyChanges(baz, "bar");

Kinda cool! I soon realized that this technique has some characteristics that Objective-C messages don’t have. For example, each step can use more than one parameter (plus they each get their own code hinting). You can also provide multiple choices for what to do next providing a sort of branching behavior.

AngleFinder.getAngleOfVector(4, 4).inDegrees() 	// 45°
AngleFinder.getAngleOfVector(4, 4).inRadians() 	// π/4

You can even do free-form stacking of functions like this.

new Calculator	(5)                    // 5
                        .plus(3)            // 8
                        .times(2)          // 16
                        .dividedBy(4)   // 4
                        .minus(1)         // 3
                        .plus(2)            // 5
                        .equals();

I proudly named these “Matryoshka Functions” after the Russian stacking dolls even though I’m sure I’m not the first to try something like this. As it turns out, they’re about 10% practical and 90% clever hack. Even though there could be some potential use for this (especially with complicated, repetitive tasks), this technique conflicts too much with the way we normally code in ActionScript. Still, I thought it was cool enough to share with everyone.

Pros:

  • Very descriptive
  • Branching and stacking effect is interesting and potentially useful
  • Code hinting shows the next step in the function as well as the parameter names
  • Looks cool!

Cons:

  • Abominable code style. Too weird to be useful.
  • Difficult to know when to stop calling functions
  • Not completing the function will produce unexpected results with no compile-time errors
  • Each step requires you to pass the parameters from the previous step

Can you find any use of these? Can you think of a more efficient way to write the functions? Any other thoughts?

Check out the source with multiple examples (FlashBuilder project).
MatroshkaFunctionDemo

Learn Yourself to Debug Good With XCode and Instruments

by

Hi! (Here Roger pretends it hasn’t been 100 years since his last posting and moves on swiftly.) So if you’ve been learning or practicing iPhone development, you might agree with me that there’s one topic that inspires a little FUD and that is covered a little sparsely by books — debugging. Between scary messages like EXC_BAD_ACCESS, uncaught exceptions deep in the guts of thorny disassembled framework code, crashes that don’t break into the debugger, and the direct interface to the gdb console, debugging in XCode can have a learning curve even if you know your way around a debugger. I’ve seen too many good men use NSLog() to debug, and it bugs me.

So here’s a few screencasts I found around town on debugging, that I wanted to share. Do yourself a favor and watch them.

First up, a series of two screencasts by Jeff LaMarche on debugging basics. I’ll reiterate, even if it starts out basic, you might learn something since it seems everyone uses the debugger differently. Part One, Part Two. Key takeaways:

  • Dude. Just drag the breakpoint out of the gutter to remove it. I’ve been right-clicking the damn thing my whole life. Sighhh….
  • XCode breakpoints are heckuv powerful. Use symbolic breakpoints, conditional breakpoints, and breakpoint actions wisely.
  • Single most important thing: Add a symbolic breakpoint on objc_exception_throw. Newer XCode builds have a menu item for this in Run→Stop on Objective-C Exceptions.

Next, a screencast on debugging EXC_BAD_ACCESS, which is raised when you access an object that has vanished into thin air, most likely because you over-released it. This screencast from Mark Johnson shows you how to debug these errors with Instruments and NSZombies. You’ll see how to generate a complete history of any object, from allocation and including every release or retain. You’ll also see how to find the objects of interest by enabling zombies (you know, after your object is completely released and freed it sticks around, undead). For those of you who see Instruments and aren’t quite sure what to do with it, just watching Mark use it is helpful. My takeaway was that it’s much easier and nicer to use Instruments than to enable zombies by hand.

Finally, here’s a nice tutorial by Owen Goss on using Instruments to find memory leaks. It’s also another good scenario which you can follow to help get your head around Instruments.

Bonus info: XCode 3.2 and later has the Clang Static Analyzer built in. This is a sweet tool that analyzes your code without running it (thus the static part). Just run Build→Build and Analyze and you’ll get a brutal report of how and where Clang thinks your code is totally sketchy. John Muchow shows you how here.

Anything that still baffles you about XCode/iPhone debugging? Care to add any other beginner debugging help? Hit the comments!