我希望在执行更新数据的插入之前清除CoreData实体中的所有数据。到目前为止,我尝试删除所有不允许我插入更新数据的内容,即使在两个操作中使用相同的上下文时也是如此。有没有更好的方法呢?这是我一直在实施的代码。我所做的是从旧记录中删除实体,然后保存上下文。然后我在上下文中插入新对象,最后,我保存它。显然,在我保存之后,当我从视图中调用存储的数据时,它将返回空。
class DS_Objectives {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let dateFormatter = NSDateFormatter()
func storeObjectives(json: JSON) {
let context:NSManagedObjectContext = appDel.managedObjectContext
self.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
self.dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
let request : NSFetchRequest = NSFetchRequest.init(entityName: "EducationalObjective")
context.performBlock{
do{
let oldObjectives = try context.executeFetchRequest(request) as! [NSManagedObject]
for obj in oldObjectives {
context.deleteObject(obj)
}
try context.save()
} catch {
print(error)
}
}
for (_,subJson):(String, JSON) in json {
var obj : EducationalObjective? = self.findObjective(Int(subJson["IdObjetivoEducacional"].stringValue)!)
if obj == nil {
obj = NSEntityDescription.insertNewObjectForEntityForName("EducationalObjective",inManagedObjectContext: context) as? EducationalObjective
obj!.setValue(Int(subJson["IdObjetivoEducacional"].stringValue), forKey: "id")
}
obj!.setValue(Int(subJson["Numero"].stringValue), forKey: "numero")
obj!.setValue(Int(subJson["IdEspecialidad"].stringValue), forKey: "especialidad")
obj!.setValue(subJson["Descripcion"].stringValue, forKey: "descripcion")
obj!.setValue(subJson["CicloRegistro"].stringValue, forKey: "cicloRegistro")
obj!.setValue(subJson["Estado"].boolValue, forKey: "estado")
obj!.setValue(self.dateFormatter.dateFromString(subJson["updated_at"].stringValue), forKey: "updated_at")
for (_,res):(String,JSON) in json["students_results"] {
var edRes : StudentResult? = self.findStudentResult(Int(res["IdResultadoEstudiantil"].stringValue)!)
if edRes == nil {
edRes = NSEntityDescription.insertNewObjectForEntityForName("StudentResult",inManagedObjectContext: context) as? StudentResult
edRes!.setValue(Int(res["IdResultadoEstudiantil"].stringValue)!, forKey: "id")
}
edRes!.setValue(Int(res["IdResultadoEstudiantil"].stringValue), forKey: "id")
edRes!.setValue(res["Identificador"].stringValue, forKey: "identificador")
edRes!.setValue(res["Descripcion"].stringValue, forKey: "descripcion")
edRes!.setValue(res["CicloRegistro"].stringValue, forKey: "cicloRegistro")
edRes!.setValue(res["Estado"].boolValue, forKey: "estado")
edRes!.setValue(self.dateFormatter.dateFromString(res["updated_at"].stringValue)!, forKey: "updated_at")
}
}
do{ try context.save() } catch { print(error) }
}
答案 0 :(得分:0)
context.performBlock
在托管对象上下文队列中异步调度提供的块。由于您使用此方法来计划删除,然后同步执行插入(并且可能在错误的队列中),您将插入新对象,然后删除所有内容。