Game Development Reference
In-Depth Information
Listing 3-6. CoinsControllerDelegate (from CoinsController.h)
@protocol CoinsControllerDelegate<NSObject>
-(void)gameDidStart:(CoinsController*)aCoinsController with:(CoinsGame*)game;
-(void)scoreIncreases:(CoinsController*)aCoinsController with:(int)newScore;
-(void)turnsRemainingDecreased:(CoinsController*)aCoinsController with:(int)turnsRemaining;
-(void)gameOver:(CoinsController*)aCoinsController with:(CoinsGame*)game;
@end
As can be seen in Listing 3-6, a protocol is a pretty simple thing. The name of the protocol comes
after the @protocol . The <NSObject > specifies what types of objects can conform to this protocol.
Between the @protocol and the @end , a number of tasks are declared. These are the messages that
are going to be sent to the delegate object, so the delegate object should implement each of these
tasks. The delegate field is declared in the interface section of the CoinsController like this:
IBOutlet id<CoinsControllerDelegate>delegate;
We also define a property for this field, with the property declaration:
@property (nonatomic, retain) id<CoinsControllerDelegate>delegate;
There are two things to notice about the declaration of the delegate property. First, we can assign
any object as the delegate. Because it is type id , we will get a compiler warning if the assigned
object is known not to conform to the protocol CoinsControllerDelegate . The second thing to notice
is that we defined it as an IBOutlet , which allows us to actually set the relationship between the
GameController object and the CoinsController object in Interface Builder. This is not required, but
it can be a handy addition if you are planning on writing code consumed by other developers.
Looking at the declaration of the class GameController , we can see that it conforms to the protocol
CoinsControllerDelegate , as such:
@interface GameController : UIViewController<CoinsControllerDelegate>{
Implementing the Defined Tasks
Simply stating that a class conforms to a protocol is just the first step. The conforming class should
also implement each task defined in the protocol. Listing 3-7 shows the implementation of the
CoinsControllerDelegate protocol in the GameController.m file.
Listing 3-7. GameController.m (CoinsControllerDelegate Tasks)
//CoinsControllerDelegate tasks
-(void)gameDidStart:(CoinsController*)aCoinsController with:(CoinsGame*)game{
for (UILabel* label in scoreLabels){
 
Search WWH ::




Custom Search