fuzzygoat
fuzzygoat

Reputation: 26223

Simple protocol example needed?

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.

Upvotes: 0

Views: 2233

Answers (2)

Chuck
Chuck

Reputation: 237010

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:

id<PetProtocol> getSomeObjectThatConformsToThePetProtocol() {
    return [[[CustomController alloc] init] autorelease];
}

int main() {
    id<PetProtocol> foo = getSomeObjectThatConformsToThePetProtocol();
    [foo printCat];
    [foo printDog];
    return 0;
}

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 to PetProtocol would do. That's what protocols are for.

Upvotes: 4

livemac
livemac

Reputation: 113

Protocol (or delegation) is used to call a method in a different class. For example, the class that contains the protocol (lets call it PetClass) would call [self.delegate printCat] and the delegated class (CustomController) would carry that method out for the PetClass object.

This might help as well:

delegation: the assignment of authority and responsibility to another person (normally from a manager to a subordinate) to carry out specific activities

This assumes of course you have defined self.delegate in your header and synthesized it in your implementation:

Header iVars:

id <PetProtocol> delegate;

Implementation:

@implementation PetClass
@synthesize delegate;

Upvotes: 2

Related Questions