• 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> 被点击






  • 相关阅读:
    C#XML操作详解
    浏览器检测JS代码(兼容目前各大主流浏览器)
    C# DataTable 详解
    MyEclipse设置java文件每行字符数
    springmvc,hibernate整合时候出现Cannot load JDBC driver class 'com.mysql.jdbc.Driver
    org.apache.catalina.util.DefaultAnnotationProcessor cannot be cast to org.apache.AnnotationProcessor
    hibernate使用注解生成表,有时无法生成数据表的原因
    rtthread STM32F4以太网
    STM32F4闹钟
    Keil MDK下如何设置非零初始化变量(转)
  • 原文地址:https://www.cnblogs.com/lixingle/p/3312980.html
Copyright © 2020-2023  润新知