Learning Objective-C: Protocols

by Chris at 3:21 pm

So, I’ve been learning some Objective-C to do my iPhone programming, and am gradually getting into the more interesting parts of it. Just now I’ve been playing with protocols to define some basic structures for my next iPhone game.

I guess you could say that a protocol is very similar to an interface class in c++, excepting that you can have optional methods as well as the required methods, allowing your classes to implement only the optional methods that you wish to use.

Here’s an example of a protocol definition

@protocol GameScreen

@required
-(id) init;
-(void) draw;
-(void) update:(float)time;

@optional
-(void) tapeventDragBegin:(CGPoint)origin;
-(void) tapeventDrag:(CGPoint)origin currentPosition:(CGPoint)current;

@end

Using the @required keyword indicates the methods that will be required for any class to define, while methods after the @optional keyword will not need to be implemented.

You can implement the protocol in a class by using the following code

@interface MainScreen : NSObject {
}
// required methods
-(id) init;
-(void) draw;
-(void) update:(float)time;

// optional methods
-(void) tapeventDrag:(CGPoint)origin currentPosition:(CGPoint)current;
@end

There is one other thing that you will need to consider when coding to handle optional methods, and that is the problem of whether the method has actually been implemented or not. Fortunately, you can use the respondsToSelector method to check if it’s been implemented prior to calling it.

if([myScreen respondsToSelector:@selector(tapeventDrag:currentPosition:)]){
[myScreen tapeventDrag:origin currentPosition:current];
}