Over a million developers have joined DZone.

Elegant Delegation in Objective-C

· Mobile Zone

Here’s a worthwhile read on the merits of analyzing your delegate’s implementations at the point of setting instead of at every call:

Fast and elegant delegation in Objective-C

If you call an optional delegate protocol, and it grows larger and larger, you find yourself write variations of this ugly block all over your code:

if ([self.delegate respondsToSelector:@selector(pdfViewController:didDisplayDocument:)]) {

[self.delegate pdfViewController:self didDisplayDocument:self.document];

}

I consider this code smell, and it doesn’t get easier once you decide to change the delegate. While developing PSPDFKit (a commercial, extremely fast iOS pdf framework), i found myself in the situation of polluting my code with those delegate calls all over the place. There has to be a better way…

… A pattern that’s common in Apple classes is to pre-analyze the delegate, and remember which methods are implemented and which aren’t. I did some profiling and discovered that this is about twice as fast…

Yep, clear benefits in maintainability and speed both, that does indeed look like a pattern worthy of adoption wethinks.

h/t: @steipete via @mariozullo!

Topics:

Published at DZone with permission of Alex Curylo, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}