Simple Delegate Example?

I won’t go into any detailed analysis of the code you posted — the most helpful response you could get is some direction as far as general principles that transcend a specific code sample. Here are the general principles…

  • A delegate is an object whose objects are (generally) called to handle or respond to specific events or actions.
  • You must “tell” an object which accepts a delegate that you want to be the delegate. This is done by calling [object setDelegate:self]; or setting object.delegate = self; in your code.
  • The object acting as the delegate should implement the specified delegate methods. The object often defines methods either in a protocol, or on NSObject via a category as default/empty methods, or both. (The formal protocol approach is probably cleaner, especially now that Objective-C 2.0 supports optional protocol methods.)
  • When a relevant event occurs, the calling object checks to see if the delegate implements the matching method (using -respondsToSelector:) and calls that method if it does. The delegate then has control to do whatever it must to respond before returning control to the caller.

In the specific example you’re working through, notice that GKPeerPickerController has a property named delegate which accepts an object of type id<GKPeerPickerControllerDelegate>. This means an id (any subclass of NSObject) that implements the methods in the GKPeerPickerControllerDelegate protocol. GKPeerPickerControllerDelegate in turn defines a number of delegate methods and describes when they will be called. If you implement one or more of those methods (the documentation says all are optional, but two are expected) and register as a delegate, those methods will be called. (Note that you don’t need to declare a method prototype in your .h file, just import the protocol header and implement the method in your .m file.

Leave a Comment