ios 代理

来源:互联网 发布:博时大数据100好买 编辑:程序博客网 时间:2024/06/06 17:25

我太忙了,雇用了一位助手,并安排了一定任务A,任务B,任务C,.. 给他。 一 接到活,属于任务A,B,C...之类的活,我自己不做,直接抛给助手去完成。

那么,“我”就是A Object.  助手”就是"我"的“Delegate”。写成代码就是: 我.delegate= 我的助手

我的助是可以实现我给他的任务A,B,C,..的,这些任务就是协议 protocol 。由我助来实现协议所声明的任务。

协议 Protocol :(类似java的接口, C++的虚基类)

我说下我的理解。object-c 里没有多继承。那么又要避免做出一个对象什么都会(super class monster,huge ,super,waste)一个超能对象本身是否定了面向对象的概念和真谛了。为了让代码更简洁,条理更清楚,可以将部分职责分离。

协议本身没有具体的实现。只规定了一些可以被其它类实现的接口

#import <Foundation/Foundation.h>


@protocol MyProtocol <NSObject>


@required 

-(void)testProFun;

@optional

-(void)testProFun2;


@end

delegate 总是被定义为 assign @property

#import <Foundation/Foundation.h>

#import "MyProtocol.h"

@interface MyProtocolRef : NSObject

{

    id<MyProtocol> _delegate;

}


@property(nonatomic,assign)id<MyProtocol>delegate;


@end

 #import "MyProtocolRef.h"

@implementation MyProtocolRef

@synthesize delegate=_delegate;


-(id)init

{

    self =[super init];

    if (self) {

    }

    return self;

}


-(void)callDelegate

{

    if ([self.delegate respondsToSelector:@selector(testProFun)]) {

        [self.delegate testProFun];

    }

    if ([self.delegate respondsToSelector:@selector(testProFun2)]) {

        [self.delegate testProFun2];


    }

    

}


@end

这样我们就在MyProtocolRef 内部声明一个委托(delegate),那么就需要委托的代理实现MyProtocol 中约定的行为


// 首先, 在接口里边声明要使用谁的Delegate   

#import <Foundation/Foundation.h>

#import "MyProtocol.h"

@class MyProtocolRef;

@interface MyProtocolImp : NSObject<MyProtocol>

{

    MyProtocolRef *_ref;

}

@end


// 然后在实现文件中初始化的时候, 设置Delegate为self(自己) ,

//并实现MyProtocol中约定的行为   


 

#import "MyProtocolImp.h"

#import "MyProtocolRef.h"


@implementation MyProtocolImp


-(id)init

{

    self=[super init];

    if (self) {

        

        _ref=[[MyProtocolRef alloc]init];

        _ref.delegate=self;

    }

    return  self;

}

-(void)dealloc

{

    [_ref release];

    _ref=nil;

[super dealloc];

}


-(void)callRef

{

    if (_ref) {

        [_ref callDelegate];

    }

}


//imp MyProtocol testProFun

-(void)testProFun

{

    NSLog(@"call testProFun");

}


//imp MyProtocol testProFun2

-(void)testProFun2

{

     NSLog(@"call testProFun2");

}


@end


0 0
原创粉丝点击