我有一个使用Core Data的应用程序。在其中有帖子,每个帖子都有很多标签。每个标签都有很多帖子。
我有一个主视图控制器,该控制器显示所有标签的集合视图。此collectionView的数据源由NSFetchedResultsController
提供支持class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource,NSFetchedResultsControllerDelegate {
@IBOutlet weak var latestTagsCollectionView: UICollectionView!
var fetchedResultsController: NSFetchedResultsController<Tag>!
var blockOperations: [BlockOperation] = []
override func viewDidLoad() {
super.viewDidLoad()
self.latestTagsCollectionView.dataSource = self
self.latestTagsCollectionView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//1
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext =
appDelegate.persistentContainer.viewContext
//2
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Tag")
//3
fetchRequest.sortDescriptors = []
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedContext, sectionNameKeyPath: nil, cacheName: nil) as? NSFetchedResultsController<Tag>
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
func configure(cell: UICollectionViewCell, for indexPath: IndexPath) {
guard let cell = cell as? TagCollectionViewCell else {
return
}
print(indexPath,"indexPath")
let tag = fetchedResultsController.object(at: indexPath)
guard let timeAgo = tag.mostRecentUpdate as Date? else { return }
cell.timeAgo.text = dateFormatter.string(from: timeAgo)
if let imageData = tag.mostRecentThumbnail {
cell.thumbnail.image = UIImage(data:imageData as Data,scale:1.0)
} else {
cell.thumbnail.image = nil
}
cell.tagName.text = tag.name
cell.backgroundColor = UIColor.gray
}
//CollectionView Stuff
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let sectionData = fetchedResultsController.sections?[section] else {
return 0
}
return sectionData.numberOfObjects
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = latestTagsCollectionView.dequeueReusableCell(withReuseIdentifier: "latestTagCell", for: indexPath) as! TagCollectionViewCell
configure(cell: cell, for: indexPath)
return cell
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange anObject: Any,
at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType,
newIndexPath: IndexPath?){
switch type {
case .insert:
print("Insert Object: \(String(describing: newIndexPath))")
blockOperations.append(
BlockOperation(block: { [weak self] in
if let this = self {
this.latestTagsCollectionView!.insertItems(at: [newIndexPath!])
}
})
)
case .update:
blockOperations.append(
BlockOperation(block: { [weak self] in
if let this = self {
this.latestTagsCollectionView!.reloadItems(at: [newIndexPath!])
}
})
)
case .move:
blockOperations.append(
BlockOperation(block: { [weak self] in
if let this = self {
this.latestTagsCollectionView!.moveItem(at: indexPath!, to: newIndexPath!)
}
})
)
case .delete:
print("deleted record")
blockOperations.append(
BlockOperation(block: { [weak self] in
if let this = self {
this.latestTagsCollectionView!.deleteItems(at: [newIndexPath!])
}
})
)
default: break
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
latestTagsCollectionView!.performBatchUpdates({ () -> Void in
for operation: BlockOperation in self.blockOperations {
operation.start()
}
}, completion: { (finished) -> Void in
self.blockOperations.removeAll(keepingCapacity: false)
})
}
deinit {
// Cancel all block operations when VC deallocates
for operation: BlockOperation in blockOperations {
operation.cancel()
}
blockOperations.removeAll(keepingCapacity: false)
}
在其他视图控制器上,我允许用户添加帖子。用户可以为每个帖子添加许多不同的标签。这是保存帖子时调用的方法:
func save(){
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext =
appDelegate.persistentContainer.viewContext
var postTags:[Tag] = []
if let tokens = tagsView.tokens() {
for token in tokens {
let tagFetchRequest: NSFetchRequest<Tag> = Tag.fetchRequest()
tagFetchRequest.predicate = NSPredicate(format: "name == %@", token.title)
do {
let res = try managedContext.fetch(tagFetchRequest)
var tag: Tag!
if res.count > 0 {
tag = res.first
} else {
tag = Tag(context: managedContext)
tag.name = token.title
tag.mostRecentUpdate = NSDate()
tag.mostRecentThumbnail = UIImage(named: "Plus")!.pngData() as! NSData
}
postTags.append(tag)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
return
}
}
}
let post = Post(context: managedContext)
for tag in postTags {
tag.addToPosts(post)
post.addToTags(tag)
}
post.mediaURI = URL(string: "https://via.placeholder.com/150")
post.notes = "some notes..."
post.timeStamp = Calendar.current.date(byAdding: .day, value: 8, to: Date()) as! NSDate
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
如您所见,每个标签要么在数据库中被识别,要么在不存在的情况下被创建。对于此错误,我开始时数据库中没有数据。首先,我创建一个带有标签“ one”的帖子。然后,我回到主视图控制器的视图。我看到一个名为“ One”的新标签已创建。
Insert Object: Optional([0, 0])
当.insert大小写应用于NSFetchedResultsController的回调方法时,会打印。
然后我添加一个带有两个标签的帖子:“一个”,“两个”。
Insert Object: Optional([0, 0])
2018-12-05 12:51:16.947569-0800 SweatNetOffline[71327:19904799] *** Assertion failure in -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKitCore_Sim/UIKit-3698.84.15/UICollectionView.m:5908
2018-12-05 12:51:16.949957-0800 SweatNetOffline[71327:19904799] [error] fault: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. attempt to delete item 1 from section 0 which only contains 1 items before the update with userInfo (null)
为什么在这里尝试删除项目1 ...我不太了解此错误消息。我相信它应该只是在新的索引路径中插入一个项目,因为已经在数据库中创建了一个新的标记“ Two”。这里发生了什么?
答案 0 :(得分:1)
您的问题是由在newIndexPath
情况下使用indexPath
而不是.update
引起的。
将现有标签分配给帖子时,该Tag
对象将更新。这将导致.updated
事件被发布到NSFetchResultsControllerDelegate
。
在委托方法中,newIndexPath
表示对象 插入后的索引路径,而indexPath
代表对象 before <的索引路径。 / em>插入。
performBatchUpdates:completion
的文档指出:
删除操作在插入批处理操作之前进行。这意味着在批处理操作之前,将相对于集合视图状态的索引处理删除的索引,而在批处理操作中所有删除之后,将相对于状态视图的索引处理插入的索引。
在最后一次执行插入操作时,当您尝试重新加载newIndexPath
时会遇到异常,因为您试图重新加载尚未插入的元素。
在这种情况下,更改代码以引用indexPath
即可解决问题。
case .update:
blockOperations.append(
BlockOperation(block: { [weak self] in
if let this = self {
this.latestTagsCollectionView!.reloadItems(at: [indexPath!])
}
})
)
此外,您只需要更新Post
或 Tag
;由于存在反向引用,因此核心数据将负责更新其他对象