iOS:Swift:CoreData:值未使用 PrivateManagedObjectContext 存储

iOS:Swift:CoreData: Values are not stored using PrivateManagedObjectContext

在我的应用程序中,我使用了一个 class(比如 CoredataHandler.swift)来存储和检索对象。我关注了 this tutorials 。我使用了 策略 2:Parent/Child 托管对象上下文。 但是对象没有存储在核心数据中。我没有使用 NSOperation,而是使用了普通的 class 对象。

class CoreDataHandler: NSObject {

//static var sharedInstance:CoreDataHandler = CoreDataHandler()

var privateManagedObjectContext:NSManagedObjectContext?
var mainManagedObjectContext:NSManagedObjectContext?


 override init() {

    print("core data handler constructor called")
    super.init()

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let privateManagedObjectContextlocal = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    privateManagedObjectContextlocal.parentContext = appDelegate.managedObjectContext

    self.privateManagedObjectContext = privateManagedObjectContextlocal

    self.mainManagedObjectContext = appDelegate.managedObjectContext

    let notificationCenter = NSNotificationCenter.defaultCenter()
    notificationCenter.addObserver(self, selector: #selector(CoreDataHandler.managedObjectContextDidSave(_:)), name: NSManagedObjectContextDidSaveNotification, object: privateManagedObjectContext)
}

private func insertData(entityName:String,dataDictionary:Dictionary<String, AnyObject?>){
    synced(self) { () -> () in

        //        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

        let entityDescription = NSEntityDescription.entityForName(entityName, inManagedObjectContext: self.privateManagedObjectContext!)

        let newPerson = NSManagedObject(entity: entityDescription!, insertIntoManagedObjectContext: self.privateManagedObjectContext!)

        for (myKey, myVal) in dataDictionary {

            if myVal is Int {

                if let result_number = myVal as? NSNumber
                {
                    let result_string = "\(result_number)"
                    newPerson.setValue(result_string, forKey: myKey)

                }


            }else{
                newPerson.setValue(myVal, forKey: myKey)

            }

        }

        //print("insertData",newPerson)

        do {
            if ((self.privateManagedObjectContext?.hasChanges) != nil){

                try self.privateManagedObjectContext!.save()
            }



        } catch {

            // Replace this implementation with code to handle the error appropriately.

            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            let nserror = error as NSError

            NSLog("Unresolved error \(nserror), \(nserror.userInfo)")

            abort()

        }
    }
}

// MARK: - Insert

func insertOfferObjects(arrOffer : Array<FoodItem>?) {
    synced(self) { () -> () in


        //Step1: Adding Offer Items
        if let _ = arrOffer {
            var foodArr:Array<NSManagedObject> = Array()

            for foodObj : FoodItem in arrOffer! {

                let offerItemEntity = self.createFoodItemEntity(foodObj)
                foodArr.append(offerItemEntity)

            }

            self.insertData("OfferCategory", dataDictionary: ["categoryTitle": "Offers", "foodItemArray": NSOrderedSet(array: foodArr)])

        }
    }
}

值未存储在核心数据中。请给我最好的方法。

已编辑:更新::来自答案,需要在子上下文时保存父项 已保存

            self.privateManagedObjectContext?.performBlockAndWait({ 

                if ((self.privateManagedObjectContext?.hasChanges) != nil){

                     do {

                        print("It has changes...............")

                        try self.privateManagedObjectContext!.save()

                        self.mainManagedObjectContext?.performBlock({
                            do {
                            try self.mainManagedObjectContext!.save()
                            }catch{

                            }
                        })

                     }catch {

                        // Replace this implementation with code to handle the error appropriately.

                        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                        let nserror = error as NSError

                        NSLog("Unresolved error \(nserror), \(nserror.userInfo)")

                        abort()

                    }

                }
            })

保存子上下文只会将这些更改推送到父上下文。除非您还保存父上下文(将更改推送到持久存储),否则您的更改将不会写入磁盘。

来自 NSManagedObjectContext class 参考:

When you save changes in a context, the changes are only committed “one store up.” If you save a child context, changes are pushed to its parent. Changes are not saved to the persistent store until the root context is saved. (A root managed object context is one whose parent context is nil.)

如果您是核心数据的新手,我建议您不要担心并发性和多上下文,除非您确实遇到需要解决它的问题。除非您正在处理数以千计的记录,或者您有兴趣为可逆更改创建编辑上下文,否则单个主线程上下文将完成您需要的一切。