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.

  • 相关阅读:
    oracle插入数据
    保存图片
    ASCII码排序及md5加密
    JavaScript
    HTML
    py访问Redis和zk操作
    Zookeeper集群搭建以及python操作zk
    并发编程
    Python之socket(套接字)
    Python 网络编程
  • 原文地址:https://www.cnblogs.com/hxxy2003/p/2222838.html
Copyright © 2011-2022 走看看