我有一个TableView从核心数据中获取数据。Swift TableView插入新行
在数据保存后,它们将作为第一行插入。
这里是我用来保存数据的代码(我没有使用获取控制器,因为我没有获取任何数据,只是加载它们,这是因为我加载的日期来自一个一对多关系)
swimToConnect.addToMaterialsLocal(materialLocal)
ad.saveContext()
// Adding the new row to update the tableView
let MyMaterialsVC = self.presentingViewController?.presentingViewController?.presentingViewController as! MyMaterialsVC
MyMaterialsVC.myMaterials.insert(materialLocal, at: 0)
MyMaterialsVC.tableView.insertRows(at: [NSIndexPath(row: 0, section: 0) as IndexPath], with: .none)
MyMaterialsVC.dismiss(animated: true, completion: nil)
}
所以我想知道是否有方法插入按日期排序的行。 我已经命令他们按日期,像这样:
var swim: SwimminPool! {
didSet {
myMaterials = (swim.materialsLocal?.allObjects as! [MaterialLocal]).sorted(by: {$0.createdAtLocal! > $1.createdAtLocal!})
}
}
在哪里创建是一个日期选择器,用户添加的日期。 当我保存新数据显然他们显示在第一行,但如果我解雇了控制器,然后回来,然后数据显示根据日期顺序。
有没有办法在我保存后立即以正确的顺序排列数据?
谢谢。
你为什么不重新加载表视图只是增加了数据之后。正如我在加载视图时所了解的那样,表视图按日期排序显示数据。因此,而不是在表视图中插入行,只需将数据保存在核心数据中,然后重新加载表视图 –
您的意思是删除这两行:MyMaterialsVC.myMaterials.insert(materialLocal,位于:0) MyMaterialsVC.tableView .insertRows(在:[NSIndexPath(row:0,section:0)as IndexPath],其中:.none) – Marco
当您将其保存在核心数据中并应用排序时,在此之后您可以重新加载数据表视图,其数据源是您的核心数据。 –