所以我正在使用JSQMessagesViewController构建一个消息传递应用程序。我将它链接到fetchedResultsController,它每次将新对象插入上下文时都会跟踪。在didPressSend中我插入上下文:
override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
let message = NSEntityDescription.insertNewObject(forEntityName: "Message", into: context) as! Message
message.text = text
message.timestamp = Date() as NSDate?
}
所以每当我使用DidPressSend(发送按钮)将新对象插入上下文时,取出的结果控制器就会被激活
var InsertOperation = [BlockOperation]()
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
if type == .insert {
InsertOperation.append(BlockOperation(block: { [weak self] in
self?.collectionView.collectionViewLayout.invalidateLayout()
self?.collectionView.insertItems(at: [newIndexPath!])
DispatchQueue.main.async {
self?.scrollToBottom(animated: true)
}
}))
}
}
然后在didChangeContent
中执行块操作func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
collectionView.performBatchUpdates({
for operation in self.InsertOperation {
operation.start()
self.InsertOperation.removeFirst()
}
})
}
最后将该项插入到didPressSend中创建的集合视图中。首先,它以惊人的速度插入它们。一切都很棒!然而,当我在collectionView中获得100个左右的项目时,它开始变得越来越迟缓。我的collectionView委托方法中没有任何花哨的东西。简单地说就是这样:
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
let msg : Message = fetchedResultsControler.object(at: indexPath) as! Message
let messageData = JSQMessage(senderId: senderId, displayName: senderDisplayName, text: msg.text)
return messageData
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (fetchedResultsControler.sections?[0].numberOfObjects)!
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell
return cell
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! {
let bubbleFactory = JSQMessagesBubbleImageFactory()
return bubbleFactory?.outgoingMessagesBubbleImage(with: .black)
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
return nil
}
我没有将其包含在代码中,但是当用户按下后退按钮并返回聊天时,它会将聊天分页只显示最后20条消息,使其再次超高速。但是,用户很可能在按下之前发送大量消息,并为集合视图提供分页的机会。结果,当用户聊天时,用户体验会严重减少。我注意到像tinder一样的应用程序(我测试过它),你可以一次发送1000条消息,什么都不会减慢。必须有一个我无法弄清楚的技巧。 谢谢!