How to save fetched results to a different CoreData entity with same properties

Hello:


I have successfully fetched data from an entity in my CoreData store "SCQ". I am able to use the data with all properties. Now I want to move that fetched data to a backgroundContext and save it to a new entity in the CoreData store "TempSCQ". When I try to save no data is available.

Any help will be appreciated.

Here is my code:


guardlet appDelegate = NSApplication.shared.delegate as? AppDelegate  else {
       
                       return
                }
       
              //     print ("Step Four")
        _ = appDelegate.persistentContainer.viewContext
       
        let fetchRequest = NSFetchRequest(entityName: "SCQ")
        fetchRequest.returnsObjectsAsFaults = false
       
        // And Predicate
       
        let predicate1 = NSPredicate(format: "grade = %@",nameGrade)
        let predicate2 = NSPredicate(format: "qid = %i", count)
       
        fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1,predicate2])
       
       
          do {
                   
            items =  try managedContext.fetch(fetchRequest)
            print ("Records fetched is \(count)" )
            print ("selected grade is \(nameGrade)")
            print ("Number is \(count)")
            print ("Group Name is \(nameGroup)")
           
                } catch let error as NSError {
                   
                    print("Could not fetch. \(error), \(error.userInfo)")
                }

    let backgroundContext = persistentContainer.newBackgroundContext ()
//   var saveItems = NSEntityDescription.insertNewObject(forEntityName: "SCQ", into: backgroundContext)
       
    persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
           
    let entity = NSEntityDescription.entity(forEntityName: "TempSCQ", in: backgroundContext)!
       
        let component = NSManagedObject(entity: entity, insertInto: backgroundContext)
        for item in items {
            if let record = item.value(forKey: "answer") as? String {
            answerItem.append(record)
        }
            if let record = item.value(forKey: "difficultyLevel") as? String {
                difficultyLevelItem.append(record)
            }
            if let record = item.value(forKey: "dictractor1") as? String {
                 distractor1Item.append(record)
             }
            if let record = item.value(forKey: "dictractor2") as? String {
                 distractor2Item.append(record)
             }
            if let record = item.value(forKey: "dictractor3") as? String {
                 distractor3Item.append(record)
             }
            if let record = item.value(forKey: "dictractor4") as? String {
                 distractor4Item.append(record)
               
            }
            if let record = item.value(forKey: "dictractor5") as? String {
                distractor5Item.append(record)
            }
            if let record = item.value(forKey: "grade") as? String {
                gradeItem.append(record)
            }
            if let record = item.value(forKey: "id") as? String {
                idItem.append(record)
            }
            if let record = item.value(forKey: "qid") as? String {
                qidItem.append(record)
            }
            if let record = item.value(forKey: "question") as? String {
                questionItem.append(record)
            }
            if let record = item.value(forKey: "qValue") as? String {
                qValueItem.append(record)
            }
            if let record = item.value(forKey: "skill") as? String {
                skillItem.append(record)
            }
            if let record = item.value(forKey: "subject") as? String {
                subjectItem.append(record)
            }
            if let record = item.value(forKey: "topic") as? String {
                topicItem.append(record)
            }
                    do
                    {
                        try backgroundContext.save()
                        items.append (component)
                        print("saved")
                    }
                    catch
                    {
                       
            }
           
}


Here are the debug results:


Records fetched is 397

selected grade is 8

Number is 397

Group Name is ScorCent


CoreData: sql: INSERT INTO ZTEMPSCQ(Z_PK, Z_ENT, Z_OPT, ZANSWER, ZDIFFICULTYLEVEL, ZDISTRACTOR1, ZDISTRACTOR2, ZDISTRACTOR3, ZDISTRACTOR4, ZDISTRACTOR5, ZGRADE, ZID, ZQVALUE, ZQID, ZQUESTION, ZSKILL, ZSUBJECT, ZTOPIC) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

CoreData: details: SQLite bind[0] = (int64)5

CoreData: details: SQLite bind[1] = (int64)9

CoreData: details: SQLite bind[2] = (int64)1

CoreData: details: SQLite bind[3] = nil

CoreData: details: SQLite bind[4] = nil

CoreData: details: SQLite bind[5] = nil

CoreData: details: SQLite bind[6] = nil

CoreData: details: SQLite bind[7] = nil

CoreData: details: SQLite bind[8] = nil

CoreData: details: SQLite bind[9] = nil

CoreData: details: SQLite bind[10] = nil

CoreData: details: SQLite bind[11] = nil

CoreData: details: SQLite bind[12] = nil

CoreData: details: SQLite bind[13] = nil

CoreData: details: SQLite bind[14] = nil

CoreData: details: SQLite bind[15] = nil

CoreData: details: SQLite bind[16] = nil

CoreData: details: SQLite bind[17] = nil

CoreData: sql: COMMIT

CoreData: sql: pragma page_count

CoreData: annotation: sql execution time: 0.0000s

CoreData: sql: pragma freelist_count

CoreData: annotation: sql execution time: 0.0000s

CoreData: sql: pragma incremental_vacuum(25)

CoreData: annotation: sql execution time: 0.0002s

saved

Replies

In the Core Data model editor, a fetched property is added simply like an attribute or a relationship. ... The Destination is the entity that will be returned by way of the fetched property. The predicate is a string representation of the NSPredicate configured within the NSFetchRequest

Hello Stoweny:


Thanks for responding, but I have no idea what you mean by your answer.

My question is simply this:


When I do a Fetch, I am able to display some of the Results or all of it which suggests that those results are stored in memory. Can I move the results attributes into variables which i can then save back into a different CoreData entity?

Hello:

I found a solution:


1. i created two entities in CoreData

2. I created a managedContext and a backgroundContext

3. I implemented a fetchRequest from one entity in my CoreData store into my managedContext

4. With my Fetched Results in my managedContext

5. I read the Fetched objects one at a time into the backgroundContext then saved each one simultaneously into the other entity

I however, ran into another issue:


i need a fresh copy of the backgroundContext each time i run the function otherwise the newest data in APPENDED to the old data which I dont want!


Is there a way to replace the previous data in my backgroundContext?