January 2007 Archives
Since my previous entry on optimizing Objective-C delegates, I ran across an article on borkware.com called Elegant Delegation. The article goes over a technique that uses a proxy to forward messages to the delegate, called MDelegateManager. The proxy just eats the message if the delegate does not respond to it. This is a very clever and elegant solution, especially if the delegate does not return any value.
I actually tried to implement something similar, but could not figure out a way to stop the "selector not recognized" exception. The magic is the "undocumented" signatureWithObjCTypes: method of NSMethodSignature. I put that in quotes because this method has been known for some time now. Apparently, anyone doing anything with proxies is already aware of it. Though, now that I understand why it's used, we can actually use public methods for this case (I'll cover that later).
In this second part, I'll go over how MDelegateManager stacks up against my other techniques in readability and performance. I'll also see if using a C++ map, instead of an NSMutableDictionary, can help the miserable performance of my respondsToSelector: cache, by avoiding boxing and unboxing of selectors and booleans into objects.
I've been writing some code that uses the delegate pattern, and it was getting a little ugly and beginning to smell. In case you're not familiar writing your own delegates, here is the standard technique to call a delegate method of a class:
- (void) someMethod {
if ([delegate respondsToSelector: @selector(operationShouldProceed)]) {
if ([delegate operationShouldProceed]) {
// do something appropriate
}
}
}
This class had quite a few delegates, and the respondsToSelector: check was affecting readability. It's also theoretically faster to cache the check in an ivar, so it's not called everytime. I've used delegates before, but I wanted to explore my options, this time. In my quest to optimize for readability and performance, I got a few surprises. I'll go over the steps, and the final results of my investigation.
