基本上我为解决此类问题所做的工作是:
我没有使用符合 JSQMessageData 的 CoreData 对象,而是使用了一种叫做 viewModel 的东西。
ViewModel 基本上是一个普通的 NSObject,它只是从 CoreData 对象中解包所有必要的信息并符合 JSQMessageData 协议——提供文本、senderId 和其他信息(如果需要,还提供媒体消息)
@interface ChatMessageViewModel : NSObject <JSQMessageData>
@property (nonatomic, strong, readonly) CDChatMessage *chatMessage;
// main properties
@property (nonatomic, copy, readonly) NSString *text;
@property (nonatomic, copy, readonly) NSString *senderId;
@property (nonatomic, copy, readonly) NSString *watcherId;
...
@property (nonatomic, strong, readonly) JSQMessage *mediaMessage;
- (instancetype)initWithChatMessage:(CDChatMessage *)chatMessage;
@end
.m 文件可能如下所示:
@interface ChatMessageViewModel ()
@property (nonatomic, strong, readwrite) CDChatMessage *chatMessage;
// main properties
@property (nonatomic, copy, readwrite) NSString *text;
@property (nonatomic, copy, readwrite) NSString *senderId;
@property (nonatomic, copy, readwrite) NSString *watcherId;
...
@property (nonatomic, strong, readwrite) JSQMessage *mediaMessage;
@end
@implementation ChatMessageViewModel
- (instancetype)initWithChatMessage:(CDChatMessage *)chatMessage
if (self = [super init]) {
_chatMessage = chatMessage;
[self unpackViewModel];
}
return self;
}
- (void)unpackViewModel {
self.senderId = self.chatMessage.senderId;
self.text = self.chatMessage.senderId;
self.mediaMessage = [self unpackMediaData];
}
- (JSQMessage *)unpackMediaData {
// Here CDCustomPhotoMediaItem is a subclass of JSQPhotoMediaItem which just lets me create custom look of JSQ media item.
JSQPhotoMediaItem *photoItem = [[CDCustomPhotoMediaItem alloc] init];
return [JSQMessage messageWithSenderId:self.senderId displayName:@"" media:photoItem];
}
使用 NSFetchResultsController 获取数据后,我只需获取所有核心数据对象并将它们转换为不可变的视图模型。
然后在 cellForItemAtIndexPath 我只是这样称呼:
cell.mediaView = [viewModel.media mediaView];
这种方法创建了很好的不可变包装器,它只包含 JSQ 聊天库所需的必要信息块。此外,您可以轻松地为此类对象编写测试。如果您使用的是 swift,则可以将 struct 用于这种目的。
希望我的回答有帮助。请问您是否需要更详细的答案。;-)