这里我用到了一个唱歌的,一个跳舞的,一个指挥,作为委托例子:
协议声明:
@protocol PRRPerformance_Protocol <NSObject>
-(void)performSomeAction;
@end
舞者:
@implementation Dancer
-(void)performSomeAction
{
NSLog(@"left left right right");
}
@end
歌者:
@implementation Singer
- (void)performSomeAction
{
NSLog(@"HA li lu ya!");
}
@end
它们同时遵从上面的协议,马戏团指挥有一个属性:
@interface Conductor : NSObject
@property id <PRRPerformance_Protocol> performer;
-(void)lettingPerformerDoSomething;
@end
指挥的实现:
@implementation Conductor
-(void)lettingPerformerDoSomething
{
[[self performer]performSomeAction];
}
@end
使用委托:
int main(int argc, const char * argv[]) {
@autoreleasepool {
Dancer *d = [[Dancer alloc]init];
Singer *s = [[Singer alloc]init];
Conductor *c = [[Conductor alloc]init];
//让表演者为舞者
c.performer = d;
//舞者跳舞
[c lettingPerformerDoSomething];
//让表演者为歌者
c.performer = s;
//歌者唱歌
[c lettingPerformerDoSomething];
//上面的就相当于数据源是不同对象,然后显示器对象将不同数据源显示到屏幕上,它不关心数据源的类型,只要数据源遵从特定协议(这里的协议是PRRPerformance_Protocol),就可以使用它来输出。
}
return 0;
}
输出如下:
left left right right
HA li lu ya!