Search code examples
swiftcore-datansmanagedobjectnsmanagedobjectcontext

Core Data syncing in Swift


I'm trying to link a NSManagedObject that i have just created from a json to an another NSManagedObject that is already saved, but I can't get it to work.

Basically, my function look like this, when I need to display details :

func downloadDetails(){context context: NSManagedObjectContext, main:MainEntity, completion () -> Void {

    // First, I'm getting the matching object in the right context 

    if let matchingMain = try context.existingObjectWithID(show.objectID) as? MainEntity {

    // Then, i'm making a request for the details from my main object and 
    // looping inside the json response.
    // Problem: main and matchingMain are wiped out from memory after 
    // the first iteration, and the loop throws an error when i try to make

    fetchDetails()        
    for detailJSON in try detailsJSON.children()  {
       let detail = new DetailFromJson(detailJson)
       // I get an error on the second item because matchingMain data 
       // is no longer here ("data: <fault>")
       detail.main = matchingMain          
    }
    saveContexts()
    completion()
}

I'm pretty new to this, so it might be the wrong way.

But if someone could explain me how to retain the data long enough to set it correctly, it would be great. Thanks.


Solution

  • /// UPDATE ///

    Ok, so it turns out you can't pass your managed object as an argument and expect it to stay in memory.

    I solved the problem by making a fetch request for my main managed inside my function instead (and do everything inside the main context).

    Thanks for your help.