//定义一个protocol
@protocol BuyDelegate <NSObject>
-(void) BuyIt:(NSString *)str;
@end
//定义A
@interface Aclass : NSObject
//声明一个代理类型的变量 对应上面的protocol
@property (nonatomic) id<BuyDelegate> buyDele;
-(void) showIt;
@end
#import "Aclass.h"
@implementation Aclass
@synthesize buyDele;
-(void) showIt
{
//调用代理方法 具体谁去调用 还未知
[buyDele BuyIt:@"I want a iphone 6"];
}
@end
#import "Aclass.h"
//实现相关协议
@interface Bclass : NSObject<BuyDelegate>
@end
@implementation Bclass
//实现协议中的方法
-(void) BuyIt:(NSString *)str
{
NSLog(@"str is %@",str);
}
@end
然后main方法中:
//创建a、b对象
Aclass *a =[[Aclass alloc] init];
Bclass *b=[[Bclass alloc] init];
a.buyDele=b; //将a的代理设为b
[a showIt]; //执行a的showIt方法 a中[buyDele BuyIt:@"I want iphone 6s"]; 其实是[b BuyIt:@"I want iphone 6s"];
执行结果:
2014-11-20 23:02:38.777 NScodeDemo[3981:303] str is I want a iphone 6