UICollectionView didChange和CoreData约束

时间:2017-05-12 09:15:07

标签: ios core-data uicollectionview

我有通过NSFetchedResultsController链接到CoreData实体的UICollectionView。

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {

  if type == .insert {
    blockOperations.append(BlockOperation(block: {
      self.MessagesCollectionView?.insertItems(at: [newIndexPath!])
    }))
  }

  if type == .update {
    blockOperations.append(BlockOperation(block: {
      self.MessagesCollectionView?.reloadItems(at: [newIndexPath!])
    }))
  }

}


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    let count = fetchedResultsControler.sections?[0].numberOfObjects
    return count!
}
当我将唯一数据插入实体时,

UICollection正确更新。但是当我插入与唯一约束冲突的数据时 - 实体中的新记录不会插入(它的确定),但是UICollection didChange方法得到'.insert'类型的操作并插入空行!!!如何在didChange方法中找出这个约束问题?

我可以在插入之前检查DB层类中记录的存在,但在这种情况下,约束是无用的......

这是NSFetchResultController代码:

lazy var fetchedResultsControler in UICollectionView: NSFetchedResultsController<ChatMessages> = {

    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ChatMessages")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "message_created", ascending : true)]
    fetchRequest.includesPendingChanges = false
    let frc = NSFetchedResultsController(fetchRequest: fetchRequest,
                                         managedObjectContext: context,
                                         sectionNameKeyPath: nil,
                                         cacheName: nil )
    frc.delegate = self
    return frc as! NSFetchedResultsController<ChatMessages>

}()

以下是核心数据插入代码:

    let newValue = NSEntityDescription.insertNewObject(forEntityName: "ChatMessages", into: context) as NSManagedObject
    newValue.setValue(text, forKey: "text")
    newValue.setValue(message_id, forKey:"message_id")
    let parentContext = delegate.persistentContainer.viewContext
    parentContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
    context.parent = parentContext


    context.performAndWait {
        do
        {
            dump(value)
            try context.save()
            print("Obj prepared for saving:")
            print(value)

            parentContext.performAndWait {

                do {
                    try parentContext.save()
                } catch {
                    print("Failture to save context: \(error)")
                    parentContext.rollback()
                }
            }
        }
        catch
        {
            print("Object exists...")
            context.rollback()
        }
    }

0 个答案:

没有答案