I am trying to get my head round Objective-C Protocols. I have looked at the Apple docs and also relevant chapters in a couple of books that I own, but nearly always protocols seem to be defined in terms of using them as in interface to delegate objects. I understand the concept of creating the protocol definition:
@protocol PetProtocol <NSObject>
- (void)printCat;
- (void)printDog;
@end
I also understand the bit where I conform a class to a protocol:
@interface CustomController : UIViewController <PetProtocol> {
followed by implementing the required methods.
@implementation CustomController
- (void)printCat {
NSLog(@"CAT");
}
- (void)printDog {
NSLog(@"DOG");
}
I guess my question is how to use this protocol, it seems a bit strange to call, printCat and printDog from CustomController where the methods are implemented, can anyone point me at or give me a really simple example of using this protocol or similar?
much appreciated
gary.
A protocol is just a list of messages that an object can respond to. If an object conforms to a protocol, it’s saying, “I respond to these messages.” This way, you can return an object that the caller can use without having to promise that the object will be of any particular type. For example, with that protocol, you could do this:
See,
main()doesn’t need to know that the object is a CustomController — it just knows what messages you can send the object. Any class that conforms toPetProtocolwould do. That’s what protocols are for.