• 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.

  • 相关阅读:
    多线程 execute和submit区别和使用
    Linux上安装rz和sz命令
    杜恩德__百度百科
    电商类-高并发场景处理方式一
    ConcurrentHashMap源码分析(1.8)
    JVM | 为何生产环境最好保持 Xms = Xmx
    分享ProcessOn网上的干货模板
    pythonweb开发
    pyquery
    python正则
  • 原文地址:https://www.cnblogs.com/hxxy2003/p/2222838.html
Copyright © 2020-2023  润新知