我有一个didPressSend函数,该函数接收在textview中编写的文本,并将其作为String插入到上下文中。一旦插入到上下文中,NSFetchedResultsController的DidChangeContent将检测到某些内容已插入到上下文中,并相应地自动更新集合View(请记住,DidChangeContent绝对为空)。这是我为那部分编写的代码。 (使用文本创建消息是插入上下文的功能)。
func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String! ,senderDisplayName: String!, date: NSDate){
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
createMessageWithText(text, friend: friend!, context: moc, date: date)
do {
try context.save()
} catch let err {
print(err)
}
}
private func createMessageWithText(text: String, friend: Friend, context: NSManagedObjectContext, date: NSDate, isSender: Bool = false) -> Mesages {
let message = NSEntityDescription.insertNewObjectForEntityForName("Mesages", inManagedObjectContext: context) as! Mesages
message.user = friend
message.text = text
message.timestamp = date
message.isSender = isSender
friend.lastMessage = message
return message
}
}
一旦插入上下文,didChangeContent就这样检测到它并自动更新集合视图:
lazy var fetchedResultsControler: NSFetchedResultsController = {
let fetchRequest = NSFetchRequest(entityName: "Mesages")
fetchRequest.fetchBatchSize = 50
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: true)]
fetchRequest.predicate = NSPredicate(format: "user.id = %@", self.friend!.id!)
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)
frc.delegate = self
return frc
}()
func controllerDidChangeContent(controller: NSFetchedResultsController) {
}
奇怪的是,在DidChangeContent中绝对没有似乎负责填充collectionView的东西,请记住,我正在使用fetchResultsController中的对象数来填充collectionView:
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) ->
Int {
if let count = fetchedResultsControler.sections?[0].numberOfObjects {
return count
}
return 0
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell
return cell
}
override func collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! {
let msg : Mesages = fetchedResultsControler.objectAtIndexPath(indexPath) as! Mesages
let messageData = JSQMessage(senderId: "" , displayName: "Me", text: msg.text)
return messageData
}
我还有一个来自firebase的侦听器,每当有消息发送给我时,它都会立即检测到该消息,然后将其插入上下文中,进行保存,nsfetchResultsController会检测到该消息,并触发didChangeContent。奇怪的是,在那种情况下,除非我将collectionView.reloadData放在didChangeContent中,否则它不会自动更新。但是,我并不需要为didPressSend放置collectionView.reloadData,因为它神奇地自动更新了。下面以与didPressSend相同的方式将Firebase侦听器的代码插入上下文:(使用文本创建消息是插入上下文的函数)。
ref2.observeEventType(.ChildAdded, withBlock: {(snapshot2) in
let messageId = snapshot2.key
//first message ID out of 20.
let messagesRef = FIRDatabase.database().reference().child("messages").child(messageId)
messagesRef.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
let dictionary = snapshot.value as! [NSObject: AnyObject]
let timestamp = dictionary["timestamp"] as! NSNumber
let doubleTimestamp = Double(timestamp)
let date = NSDate(timeIntervalSinceReferenceDate: (doubleTimestamp))
self.createMessageWithText(dictionary["text"]! as! String, friend: friend, context: context, date: date, isSender: true)
do {
try context.save()
}
catch {
print(error)
}
private func createMessageWithText(text: String, friend: Friend, context: NSManagedObjectContext, date: NSDate, isSender: Bool = false) -> Mesages {
let message = NSEntityDescription.insertNewObjectForEntityForName("Mesages", inManagedObjectContext: context) as! Mesages
message.user = friend
message.text = text
message.timestamp = date
message.isSender = isSender
friend.lastMessage = message
return message
}
就是说,我不确定用NSfetchedResultsController为何以及如何填充collectionView。 (确实让我担心的是,DidPressSend正在填充集合视图,而没有任何形式的任何重载数据)。另外还有一个附带的错误,如果我删除了didChangeContent(如您所见,其中包含NOTHING),则didPressSend会停止自动更新。当我添加空的didChangeContent时,集合View开始自动更新(仅适用于didpressSend)。
在委托方法下实施,并且collectionView或TableView将更新同步。尽快获取新数据。
extension ViewController: NSFetchedResultsControllerDelegate {
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
}
}