IOS代理 protocol最简单的实例,没有之一。。

//定义一个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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值