ios代理模式深入了解一下

来源:互联网 发布:linux oracle多实例 编辑:程序博客网 时间:2024/05/29 03:39

首先代理的基本使用我就不说了,今天主要说一下代理的一些特殊情况

1.我们一般调用代理方法有两个

    if ([self.delegate respondsToSelector:@selector(vcReceiveInstall:)]) {        [self.delegate vcReceiveInstall:@"11"];    }    if (self.delegate) {        [self.delegate vcReceiveInstall:@"11"];    }

第一个,是判断代理是否实现了vcReceiveInstall:这个方法,如果实现了则调用并传值。
第二个,是判断代理是否不为空,也就是说代理是否存在,如果存在则调用vcReceiveInstall:方法并传值

大部份,两个方法并没有什么区别,唯一区别就是第一个具体到方法比第二个更精确一点,如果我们有时需要判断执行代理的哪个方法 而不是判断代理是否存在,那么我们就需要用第一个。

2.多个代理。
什么是多个代理呢?假设我们是做一个tcp实时数据传输,那么你肯定会不断收到不同消息类型来进行页面分发,这个时候我们是不是需要一个单例,然后在单例里面定义代理呢?
那么这个时候,一个代理显然是不够的,因为既然是单例,如果只用一个代理,那么单例中的代理只有一个,会导致停留在哪个页面,哪个页面顶替之前页面成为其代理,则我们需要向其他页面分发消息时,无法使用代理进行传达消息。这个时候,我们只能给哪些所有需要特tcp传输消息的页面定制代理,也就是每个页面都有一个自己的代理。这样则就达到了,消息分发时,多个代理互不影响,达到我们想要的效果。不说了 ,上个demo更容易理解。

单例模式下的多代理代码

#import <Foundation/Foundation.h>@protocol DistributeDataDelegate<NSObject>@optional- (void)vcCompanyImageIson;- (void)vcReceiveInstall:(NSString *)str;@end@interface DistributeData : NSObject+ (DistributeData *)shareData;@property (nonatomic,   weak) id<DistributeDataDelegate>delegate;@property (nonatomic,   weak) id<DistributeDataDelegate>delegatee;-(void)ceshi;@end
#import "DistributeData.h"static DistributeData *_distributeData = nil;@implementation DistributeData+ (DistributeData *)shareData{    if (_distributeData==nil) {        _distributeData = [[DistributeData alloc] init];    }    return _distributeData;}- (id)init{    if (self = [super init]) {    }    return self;}-(void)ceshi{    NSLog(@"测试开始,假设tcp从这里收到消息开始分发");    if ([self.delegatee respondsToSelector:@selector(vcCompanyImageIson)]) {        [self.delegatee vcCompanyImageIson];    }    if ([self.delegate respondsToSelector:@selector(vcReceiveInstall:)]) {        [self.delegate vcReceiveInstall:@"11"];    }}@end

这样,我们可以用一个vc作为self.delegatee的代理,接收到vcCompanyImageIson方法调用。用另一个vc作为self.delegate的代理,接收vcReceiveInstall:方法并对传值进行展示。

例如:qq,qq的动态页面时self.delegatee的代理,qq的消息页面是self.delegate的代理。不能用同一个代理,是因为,假如我们消息页面成为代理,可以接收消息,由于是单例,当我们点击动态页面时,那么这个单例的代理就变成了动态页面,那么消息页面不再是代理,就不能执行代理方法了。

0 0
原创粉丝点击