Question

I understand how to make a class conform to several protocols, but where and how do I define a protocol that will be called by several classes, i.e.

_delegate.doStuff

could appear in several classes.

Was it helpful?

Solution

In xcode,

File-> New File-> Objective-c Protocol

@protocol myProtocolName

- (void) doStuff; 

@end

then in classes you want to implement this protocol

... 
#import "myProtocol.h"
@interface aClass <myProtocolName>
...

You can add this to any number of classes.

OTHER TIPS

Just make a new protocol definition -- usually in a nicely #import'able .h file. In Xcode, this is under File, New, "Objective-C Protocol".

Here's a fun little example of two protocols, and some required and optional methods and properties. Note that properties on protocols must be synthesized in classes that conform to the protocol if the property is @required (@required is the default, so it can be left out if there is not @optional section).

// AnimalMinionType.h
@protocol AnimalMinionType <NSObject>
@required
@property (nonatomic, getter = isHerbivore) BOOL herbivore;
- (NSString *)genus;
- (NSString *)species;
- (NSString *)nickname;
- (void)doPet;
@optional
- (NSString *)subspecies;
@end

// IdiotType.h
@protocol IdiotType <NSObject>
@optional
- (void)pet:(id<AnimalMinionType>)pet didScratch:(BOOL)scratchy;
@end

// FluffyCat.h
@interface FluffyCat : NSObject <AnimalType>
@end

// FluffyCat.m
@implementation FluffyCat
@synthesize herbivore;
- (NSString *)genus { return @"felis"; }
- (NSString *)species { return @"catus"; }
- (NSString *)nickname { return @"damn cat"; }
- (void)doPet:(id<IdiotType>)anyoneOrAnything
{
    NSLog(@"meow");
    if ([anyoneOrAnything respondsToSelector:@selector(pet:didScratch:)])
        [anyoneOrAnything pet:self didScratch:@YES];
}
@end

// Owner.h
@interface Owner : NSObject <IdiotType>
@property id<AnimalMinionType> housepet;
@end

// Owner.m
@implementation Owner
- (id)init
{
    self = [super init];
    if (self)
    {
        self.housepet = [FluffyCat new];
        [self.housepet setHerbivore:@NO];
    }
    return self;
}

- (NSString *)ohACuteAnimalWhatKindIsIt
{
    return [NSString stringWithFormat:@"%@ %@",[self.housepet genus], [self.housepet species]];
}

- (void)haveALongDayAtWorkAndJustNeedAFriend
{
    if (self.housepet) [self.housepet doPet:self];
}

- (void)pet:(id<AnimalMinionType>)pet didScratch:(BOOL)scratchy
{
    if ((scratchy) && (pet == self.housepet))
    {
        NSLog(@"I HATE THAT %@", [[self.housepet nickname] uppercaseString]);
        self.housepet = nil;
    }
}
@end

I hope that helps. :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top