Protocol - 7

之前有一节学习的时候我认为定义协议一定会委托非本类来执行,不然直接定义相同的方法名也可以实现,完全是多此一举,随着阅读代码量的提高我发现我错了。

在学习setFrame方法实现气泡聊天的时候发现一处:

delegate 和 dataSource

@protocol JSMessagesViewDelegate <NSObject>

@required

- (JSAvatarStyle)avatarStyle;
- (void)cameraPressed:(id)sender;
- (JSMessagesViewAvatarPolicy)avatarPolicy;
- (JSMessagesViewTimestampPolicy)timestampPolicy;
- (void)sendPressed:(UIButton *)sender withText:(NSString *)text;
- (JSBubbleMessageType)messageTypeForRowAtIndexPath:(NSIndexPath *)indexPath;
- (JSBubbleMessageStyle)messageStyleForRowAtIndexPath:(NSIndexPath *)indexPath;
- (JSBubbleMediaType)messageMediaTypeForRowAtIndexPath:(NSIndexPath *)indexPath;

@optional

- (BOOL)hasTimestampForRowAtIndexPath:(NSIndexPath *)indexPath;

@end


@protocol JSMessagesViewDataSource <NSObject>
@required
- (NSString *)textForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSDate *)timestampForRowAtIndexPath:(NSIndexPath *)indexPath;
- (UIImage *)avatarImageForIncomingMessage;
- (UIImage *)avatarImageForOutgoingMessage;
@optional
- (id)dataForRowAtIndexPath:(NSIndexPath *)indexPath;
@end

在JSMessagesViewController里面 定义了两个委托对象,并且实现了以上两个协议

@interface JSMessagesViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UITextViewDelegate, JSMessageInputViewDelegate>

@property (weak, nonatomic) id<JSMessagesViewDelegate> delegate;
@property (weak, nonatomic) id<JSMessagesViewDataSource> dataSource;

@end


接下来是定义了JSMessageViewController 的子类:ViewController

#import "JSMessagesViewController.h"

@interface ViewController : JSMessagesViewController

@end

在ViewDidLoad里面将代理赋予给自己!

#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //第一个疑问,这里的delegate 和 dataSource 想不通
    self.delegate = self;
    self.dataSource = self;
    
    self.title = @"ChatMessage";
    
    self.messageArray = [NSMutableArray array];
    self.timestamps = [NSMutableArray array];
     
}


后面当然是对代理方法的各种实现!

其实完全可以直接用子类重载父类的方式来实现同样的方法,但是为什么这么做?

因为这样做可以节省实现方法的环节,例如如果用子类来重载父类的方法的话,我们父类本身的方法实现该怎么样?

对,还可以大大减少耦合性!更加牛掰的是这样的实现可以模拟出多继承的效果!



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值