zoukankan      html  css  js  c++  java
  • ObjectiveC之@protocol

    @protocol是Objective-C中的接口定义方式,也就是说在一个类中通过@protocol定义接口,然后在另一个类中去实现这个接口,这也叫“代理”模式, 这种模式在ios开发中经常是会用到的。

    “代理”模式的使用:

    1.接口声明

    #import <Foundation/Foundation.h>

    //接口声明
    @protocol ProtocolExampleDelegate <NSObject>
    @required
    -(void)successful:(BOOL)success;

    @end

    @interface ProtocolTest : NSObject{
    //这个类包含该接口
    id<ProtocolExampleDelegate> delegate;

    }
    //接口变量delegate作为类ProtocolTest的属性
    @property(nonatomic,retain)id delegate;


    //定义一个方法,使完成的时候回调接口
    -(void)Complete;

    @end

    2.接口回调

    #import "ProtocolTest.h"

    @implementation ProtocolTest

    @synthesize delegate;

    -(void)complete
    {
    //回调接口,successful()由使用者负责具体实现
    [[self delegate]successful:YES];
    }

    //通过定时器模拟在任务完成时调用接口回调函数
    -(void)start
    {
    [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(complete) userInfo:nil repeats:YES];
    }


    @end

    3.接口实现

    #import <UIKit/UIKit.h>
    #import "ProtocolTest.h"

    @class Test;

    @interface Test : NSObject<UIApplicationDelegate,ProtocolExampleDelegate>
    {
    UIWindow *window;
    ProtocolTest *protocolTest;
    }

    @property(nonatomic,retain)UIWindow *window;

    @end
    #import "Test.h"
    #import "ProtocolTest.h"

    @implementation Test

    @synthesize window;
    //只实现一个方法
    -(void)successful:(BOOL)success
    {
    NSLog(@"completed");
    }


    这个例子只是理解下@protocol.

  • 相关阅读:
    元素的隐藏和显示
    dateformat-参数表
    HTTP缓存控制小结
    Shell 快捷键
    PHP中的cURL库
    选择排序法
    双系统重装windows后如何恢复ubuntu启动项
    dell 3420 独立显卡黄色感叹号不能用问题
    YUY数据转换为RGB数据,并进行灰度化处理显示
    ubuntu 15.04安装显卡驱动,出现登录界面闪烁得解决方案(dell 3420 )
  • 原文地址:https://www.cnblogs.com/hxxy2003/p/2222838.html
Copyright © 2011-2022 走看看