【问题标题】:Reload tableview after deleting from core data从核心数据中删除后重新加载tableview
【发布时间】:2016-08-22 12:09:44
【问题描述】:

单击按钮时,我正在删除CoreData 中的所有项目,但删除后应用程序将崩溃并出现此错误

致命错误:在展开可选值时意外发现 nil

我尝试过的代码:

if let rf = response{
                let fetchRequest = NSFetchRequest()
                fetchRequest.entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: moc)
                fetchRequest.includesPropertyValues = false
                let context:NSManagedObjectContext = appDel.managedObjectContext
                let moc = context
                do {
                    if let results = try moc.executeFetchRequest(fetchRequest) as? [NSManagedObject] {
                        for result in results {
                            moc.deleteObject(result)
                            self.tableView.reloadData()
                        }
                        try moc.save()

                    }
                } catch {
                    print("FAILED")
                }

【问题讨论】:

  • 同时从 tableview 数据源中移除对象
  • 我该怎么做?
  • 从数据源数组中删除结果
  • 先生能否提供代码示例
  • 类似这样的东西 tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

标签: ios swift uitableview core-data


【解决方案1】:

您需要重新初始化数组或从数组中删除所有对象,然后像这样在for loop 之后重新加载表。

for result in results {
    moc.deleteObject(result)        
}
try moc.save()
yourArray = [NSManagedObject]() //The array that you have used with UITableViewDataSource method
//OR
yourArray.removeAll()
self.tableView.reloadData()

【讨论】:

  • Cannot assign the value of type [NSManagedObject] to type[Cart]
  • 我的声望不够
猜你喜欢
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-10
  • 1970-01-01
相关资源
最近更新 更多