之前有一节学习的时候我认为定义协议一定会委托非本类来执行,不然直接定义相同的方法名也可以实现,完全是多此一举,随着阅读代码量的提高我发现我错了。
在学习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];
}
后面当然是对代理方法的各种实现!
其实完全可以直接用子类重载父类的方式来实现同样的方法,但是为什么这么做?
因为这样做可以节省实现方法的环节,例如如果用子类来重载父类的方法的话,我们父类本身的方法实现该怎么样?
对,还可以大大减少耦合性!更加牛掰的是这样的实现可以模拟出多继承的效果!