block传值:
使用背景:一个消息聊天界面 ChatVC,一个对具体消息的长按事件所对应的LongPressVC。
1.在LongPressVC.h中:
typedef void (^DeleteMessageHandle)(MessageModel * message);
typedef void (^ReSendMessageHandle)(MessageModel * message);
typedef void (^ReRecvMessageHandle)(MessageModel * message);
@property (copy , nonatomic) DeleteMessageHandle deleteMessage;
@property (copy , nonatomic) ReSendMessageHandle reSendMessage;
@property (copy , nonatomic) ReRecvMessageHandle reRecvMessage;
此处为自定义代码块。
2.在ChatVC.m中:
LongPressVC * longPVC = [[LongPressVCalloc] init];
longPVC.deleteMessage = ^(MessageModel * message){
[self deleteReloadRowWith:message];
};
longPVC.reSendMessage = ^(MessageModel * message) {
if (message.type ==TYPE_SEND_MESSAGE
|| message.type == TYPE_RECV_MESSAGE) {
[self sendMessageModel:message.content_txt];
} else {
if ([LocalStorageisExistFileWithFilePath:[LocalStoragegetDownloadPath] fileName:message.content_txt]) {
[selfsendFileName:message.content_txt FilePath:[LocalStorage getDownloadPath]];
} else {
ERRORLog(@"文件不存在");
}
}
};
longPVC.reRecvMessage = ^(MessageModel * message) {
dispatch_async(dispatch_get_main_queue(), ^{
[self receiveFilesWithMessage:message];
});
};
此处为获取从LongPressVC.m 中传过来的消息,并做相应处理。
3.当需要处理该消息时,从LongPressVC.m 中将该值传入。 使ChatVC.m中写入的代码块来处理这个消息体。
self.deleteMessage(self.messageModel);
self.deleteMessage(self.messageModel);
等等。
为使LongPressVC中的数据可以传到ChatVC中处理,我们在LongPressVC中自定义相关的代码块,并在适当的时候将值传入代码块中。在ChatVC方面,我们只需要alloc出LongPressVC的对象,并收取LongPressVC中的对象,并做处理即可。
longPVC.reRecvMessage = ^(MessageModel * message) {
// 此处做相应处理动作
dispatch_async(dispatch_get_main_queue(), ^{
[self receiveFilesWithMessage:message];
});
};