2016-06-23 2 views
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) } 
} 

답변

0

context.performBlock 스케줄 관리 오브젝트 컨텍스트의 대기열에 비동기 적으로 제공된 블록. 이 방법을 사용하여 삭제 일정을 정한 다음 동기식으로 (그리고 잠재적으로 잘못된 대기열에) 삽입을 수행하므로 새로운 객체를 삽입 한 다음 모든 것을 삭제합니다.

+0

그렇다면 삽입 후 어떻게 삭제되지 않도록 할 수 있습니까? –

+0

동일한 'performBlock' 클로저 내에서 두 동작을 모두 수행 할 수 있습니다. 당신은 자신의 'performBlock' 클로저에있는 각 액션을 수행 할 수 있으며, 클로저는 큐에 추가 된 순서대로 실행됩니다. 당신이 이미 정확한 동시성 큐에 있다는 것을 안다면'performBlock'을 완전히 피할 수 있습니다. – Jonah

+0

죄송합니다. 둘을 performBlock 클로저 안에 넣을 때 작동하지 않습니다. –