dyatesupnorth
dyatesupnorth

Reputation: 830

Swift & Core Data - Adding an entity to an existing entity

I understand questions regarding Core Data and relationships occur a lot, but this one's different I promise :)

I have two tables, a 'Job' table and a 'Scheme' table.

The scheme table is populated when the app loads, all good so far.

I understand that when I create a new 'Job' I need to fetch the right 'Scheme' and then attach that Scheme to the Job.

My trouble is, is I am already inside a temporary context while that Fetch is occurring, it just results in a nil unwrapping error and falls over, I think it's to do with me trying to perform a fetchRequest while an operation is already pending on my managedObjectContext...

Heres some code that should outline where I'm at:

for (index, object) in obj {

                    let entityName = "Job"
                    var request = NSFetchRequest(entityName: entityName)
                    request.predicate = NSPredicate(format: "id = %@", object["id"].string!)

                    var error: NSError?
                    if let results = tempContext.executeFetchRequest(
                        request,
                        error: &error
                        ) as? [NSManagedObject] {
                            if results.count != 0{

                                if let moc = self.managedObjectContext {
                                    moc.performBlockAndWait({

                                        for result in results {

                                            self.refreshDataSet(result, object: object)
                                             moc.save(nil)
                                        }

                                    })

                                }


                            }else{
                                if let moc = self.managedObjectContext {
                                    moc.performBlockAndWait({

                                        self.createJobData(object, moc: moc)
                                         moc.save(nil)
                                    })                                  
                                }
                          }
                    }

                }

So, inside the self.createJobData(object, moc: moc) bit is this:

 func createJobData(object: JSON, moc: NSManagedObjectContext){

    let work = NSEntityDescription.insertNewObjectForEntityForName("Work", inManagedObjectContext: moc) as! Work

    let schemeEntity = "Scheme"
    var request = NSFetchRequest(entityName: schemeEntity)
    request.predicate = NSPredicate(format: "id = %@", object["schemeId"].string!)


    self.managedObjectContext!.performBlock { () -> Void in
        var error: NSError?
        if let results = self.managedObjectContext!.executeFetchRequest(
            request,
            error: &error
            ) as? [Scheme] {
                if results.count != 0{
                    for result in results{
                        println(result)
                    }

                }

        }

    }

//....

}

and thats where I get confused, I tried adding another performBlock but then realised that wasn't the answer obviously...

Any help would be greatly appreciated :)

Upvotes: 0

Views: 1333

Answers (1)

Mundi
Mundi

Reputation: 80271

I recommend doing everything on the main thread context. If you cannot do that, do everything on the same background context.

If you are using a fetched results controller, it will do the lookup for you. Presumably your user has selected a Scheme, so

let scheme = fetchedResultsController.objectAtIndexPath(indexPath) as! Scheme

Use the same managed object context:

let context = scheme.managedObjectContext // or get it from your Core Data stack
let newJob = NSEntityDescription.insertNewObjectForEntityForName(
                 "Job", inManagedObjectContext: context) as! Job 
newJob.scheme = scheme
do { try context.save() } catch { /*handle error */ }

Upvotes: 3

Related Questions