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

时间:2016-07-26 06:22:09

标签: ios objective-c swift core-data core-data-migration

在我的应用程序中,我使用了一个类(比如CoredataHandler.swift)来存储和检索对象。我跟着this tutorials。我使用了策略2:父/子管理对象上下文。 但是对象不存储在coredata中。我没有使用NSOperation,而是使用了普通的类对象。

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)])

        }
    }
}

值未存储在coredata中。请提供给我最好的方法。

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

            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()

                    }

                }
            })

1 个答案:

答案 0 :(得分:5)

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

来自NSManagedObjectContext班级参考:

  

在上下文中保存更改时,更改仅提交“一个存储”。如果保存子上下文,则更改将推送到其父级。在保存根上下文之前,更改不会保存到持久性存储中。 (根管理对象上下文是父上下文为nil的上下文。)

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