我有一个collectionView。集合的第二部分由NSFetchedResultsController填充。单元格由“收件人”对象填充。在另一个viewController上,我将视频添加到核心数据。视频是与收件人对象的关系。这是一对多的关系。一个收件人可以有多个视频,但是每个视频只能有一个收件人。视频存储为NSOrderedSet。使用时
编辑:这是NSFetchedResultsController的声明
lazy var fetchedRC: NSFetchedResultsController<Recipient> = {
let fetchRequest:NSFetchRequest<Recipient> = Recipient.fetchRequest()
let reversedDescriptor = dateSortDescriptor.reversedSortDescriptor as! NSSortDescriptor
fetchRequest.sortDescriptors = [dateSortDescriptor]
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext:managedContext , sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController.delegate = self
return fetchedResultsController
}()
编辑:打算发布此方法。
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
print("I inserted")
break;
case .delete:
print("I deleted")
break;
case . update:
print("I updated")
break;
default:
print("I don't know")
}
}
即使检测到更改,它总是返回我不知道的东西。
let selectedPerson = personsArray[cellSelected] as? Recipient
guard let currentContext = selectedPerson?.managedObjectContext else {
print("I AM NOT SET")
return
}
let video = Videos(context: currentContext)
video.thumbNail = savedImageData
video.urlPath = url
video.isVideo = true
video.isVoiceMemo = false
video.isWrittenMemo = false
video.uuID = uuid
video.creationDate = NSDate()
if let videos = selectedPerson?.videos?.mutableCopy() as? NSMutableOrderedSet {
videos.add(video)
selectedPerson?.latestMemoDate = NSDate()
selectedPerson?.videos = videos
}
do {
try selectedPerson?.managedObjectContext?.save()
try video.managedObjectContext?.save()
self.tableView.reloadData()
}
catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}