Object-c学习之路五(@protocol协议)

今天模拟Button的delegate来联系一下protocol。

Button类

//  Button.h
//  Protocal
//
//  Created by WildCat on 13-7-24.
//  Copyright (c) 2013年 wildcat. All rights reserved.
//

#import <Foundation/Foundation.h>
@class Button;
//定义一个协议
@protocol ButtonDelegate <NSObject>
-(void)onclick:(Button *) button;
@end
//定义一个类 如果要作为Button的代理一定要实现ButtonDelegate
@interface Button : NSObject
@property (nonatomic,retain) id<ButtonDelegate> delegate;

-(void)click;
@end

#import "Button.h"



@implementation Button


-(void)dealloc{
   
    //释放_gelegate
    [_delegate release];
    [super dealloc];

}

-(void)click{

    NSLog(@"调用onclick方法");
    [_delegate onclick:self];
}
@end


ButtonListener类

/  ButtonListener.h
//  Protocal
//
//  Created by WildCat on 13-7-24.
//  Copyright (c) 2013年 wildcat. All rights reserved.
//

#import <Foundation/Foundation.h>
@protocol ButtonDelegate;
@interface ButtonListener : NSObject <ButtonDelegate>


@end

#import "ButtonListener.h"
#import "Button.h"
@implementation ButtonListener
-(void)onclick:(Button *)button{

    NSLog(@"Button %@ 被点击",button);
}
@end

主函数:


//
//  main.m
//  Protocal
//
//  Created by WildCat on 13-7-24.
//  Copyright (c) 2013年 wildcat. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Button.h"
#import "ButtonListener.h"
int main(int argc, const char * argv[])
{

    @autoreleasepool {
        Button *button=[[[Button alloc] init] autorelease];
        Button *button2=[[[Button alloc] init] autorelease];

        ButtonListener *listener=[[[ButtonListener alloc] init] autorelease];
        
        button.delegate=listener;
        button2.delegate=listener;
        
        [button click];
        [button2 click];
        
    }
    return 0;
}

运行结果:

2013-07-24 16:49:41.344 Protocal[1380:303] 调用onclick方法

2013-07-24 16:49:41.346 Protocal[1380:303] Button <Button: 0x100109990> 被点击

2013-07-24 16:49:41.347 Protocal[1380:303] 调用onclick方法

2013-07-24 16:49:41.347 Protocal[1380:303] Button <Button: 0x1001099e0> 被点击






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值