Delegates in Objective-C

The delegation pattern is used quite often in Objective-C, or rather in the Cocoa and Cocoa Touch frameworks. Using it is straightforward; however, when implementing a library or a framework, you should always check that the delegate object responds to the selector before actually calling the corresponding method. You do this with -respondsToSelector: as follows:

- (void)cancelButtonPressed:(id)sender {
  id delegate = self.delegate;
  if ([delegate respondsToSelector:@selector(hideViewController:animated:]) {
    [delegate hideViewController:self animated:YES];
  }
}

Otherwise, if the delegate doesn’t implement the method, your user’s application will simply crash with an exception because an unrecognized selector was sent to it. Strictly speaking, it’s only necessary for optional delegate methods. But because APIs change over time, and it’s really hard to keep track of all those changes, please make this best practice a habit that you stick to from now on.

Although this might seem trivial to experienced iOS and OS X developers, I believe it’s worth repeating because I’m still seeing this in code reviews.


Next: Idiomatic Function Names in Clojure
Previous: Enable Console Print in ClojureScript