0
我想在執行插入新數據之前清除CoreData實體中的所有數據。到目前爲止,我已經嘗試刪除所有不允許我插入新數據的東西,即使對兩個操作使用相同的上下文。有沒有更好的方法來做到這一點?這是我一直在實施的代碼。我所做的是從舊記錄中刪除實體,然後保存上下文。然後我在上下文中插入新的對象,最後,我保存它。顯然,在我保存之後,當我從視圖中調用存儲的數據時,它將返回空白。在NSManagedObjectContext中刪除後插入
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) }
}
好的,但是如何防止插入後發生刪除? –
你可以在同一個'performBlock'閉包中執行兩個動作。你可以在它自己的'performBlock'閉包中執行每個動作,那些閉包將按照它們被添加到隊列中的順序執行。如果你知道你已經在正確的併發隊列中,你完全可以避免使用'performBlock'。 – Jonah
對不起,將兩個放入performBlock關閉時不起作用 –