CInvocationGrabber is a Cocoa class to help with creating NSInvocation objects.
NSInvocation objects are Cocoa’s equivalent of “functors” and are extremely handy. But unfortunately creating them is often a pain. For example, take the following code showing how to create a simple NSInvocation:
[theInvocation setSelector:@selector(insertString:atIndex:)];
[theInvocation setTarget:theString];
NSString *theFirstArgument = "Hello World";
[theInvocation setArgument:&theFirstArgument atIndex:2];
unsigned theSecondArgument = 42;
[theInvocation setArgument:&theFirstArgument atIndex:3];
The code to create the same NSInvocation using my CInvocationGrabber class looks like this:
[[theGrabber prepareWithInvocationTarget:theString] insertString:@"Hello World" atIndex:42];
NSInvocation *theInvocation = [theGrabber invocation]
Obviously the primary benefit is that there is a lot less code. A secondary benefit is that you don’t have to store your parameters on the heap and can just pass them into the ‘grabbed’ method.
Now that I’ve been using CInvocationGrabber for a few months I find I am using NSInvocations more and more. I’m using them in places where I would normally have written a little delegate method. For example just today I needed to write code that called a method after a time delay. Normally I would have wrapped it up in a NSTimer delegate method, but with CInvocationHelper I just used the invocation variant of NSTimer. Although I wasn’t saving many lines of code in this example, I was reducing the clutter in the class.
Cocoa developers with a keen eye might spot the similarity between CInvocationGrabber and Cocoa’s NSUndoManager APIs. This code is directly inspired by NSUndoManager’s prepareWithInvocation method.