【问题标题】:Core Data returns 0 values even after saving in Context即使在 Context 中保存后,Core Data 也会返回 0 值
【发布时间】:2018-06-23 19:05:24
【问题描述】:

我有一个像这样的核心数据单例类:

  class CoreDataUtil {
    static let shared = CoreDataUtil()
    var  container:NSPersistentContainer? = AppDelegate().persistentContainer
    var mainContext:NSManagedObjectContext? = AppDelegate().persistentContainer.viewContext
    var backGroundContext: NSManagedObjectContext? = AppDelegate().persistentContainer.newBackgroundContext()

    init() {
      setup()
    }

    func setup(){
      mainContext?.mergePolicy =  NSMergeByPropertyObjectTrumpMergePolicy
      backGroundContext?.mergePolicy =  NSMergeByPropertyObjectTrumpMergePolicy
    }

    func getMainContext() -> NSManagedObjectContext {
      let context = CoreDataUtil.shared.mainContext
    return context!
    }

    func getBackgroundContext() -> NSManagedObjectContext {
      let context = CoreDataUtil.shared.backGroundContext
    return context!
    }

    func save()  {
      do {
          try backGroundContext?.save()
      }
      catch {
          print("Error while saving->",error)
      }
    }
  }

另外,我的 APpDelegate 中有 persistentContainer 代码,如下所示:

lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
    */
    let container = NSPersistentContainer(name: "CoreDataAlamo")
    let urlStore = Bundle.main.url(forResource: "CoreDataAlamo", withExtension: "momd")
    let storeDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
    let url = storeDirectory.appendingPathComponent("CoreDataAlamo.momd")
    let description = NSPersistentStoreDescription.init(url:url)
    description.shouldInferMappingModelAutomatically = true
    description.shouldMigrateStoreAutomatically = true
    container.persistentStoreDescriptions = [description]

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() 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.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}

现在,我正在使用 Alamofire 对象映射器在上下文中保存(使用 CoreDataUtil),我没有做错什么,但每次我尝试从 Core Data 获取(使用 CoreDataUtil)时,它都会返回 0 个元素。请帮忙。

我有这样使用的 NSManagedObject 子类:

public class ChildAnalytics: NSManagedObject, Mappable {

override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
super.init(entity: entity, insertInto: CoreDataUtil.shared.backGroundContext)
}

required public init?(map: Map) {
  let ctx  =  CoreDataUtil.shared.backGroundContext
  let entity = NSEntityDescription.entity(forEntityName: "ChildAnalytics", in: ctx!)
  super.init(entity: entity!, insertInto: ctx)
  mapping(map: map)
}

public func mapping(map: Map) {
  accurate_answer <- map["accurate_answer"]
  child_rank <- map["child_rank"]
  streak <- map["streak"]
  story_read <- map["story_read"]
  offline_time_spent <- map["offline_time_spent"]
  freadom_point <- map["freadom_point"]
  fread_done <- map["fread_done"]
  max_streak <- map["max_streak"]
  activity_done <- map["activity_done"]
  top_three <- map["top_three"]
  book_read <- map["book_read"]
}

}

现在,当我从 API 获得响应并将 JSON 映射到 ChildAnalytics 对象时, 并且在后台线程上调用了“必需的 init”,如果我使用 UIApplication.shared.delegate,它就不起作用。这就是我决定使用 AppDelegate() 的原因。

【问题讨论】:

    标签: ios core-data alamofire objectmapper


    【解决方案1】:

    AppDelegate() 实例化了一个新的 AppDelegate 对象,因此您将使用这些行创建三个新的应用代理:

    var 容器:NSPersistentContainer? = AppDelegate().persistentContainer var mainContext: NSManagedObjectContext? = AppDelegate().persistentContainer.viewContext var backGroundContext: NSManagedObjectContext? = AppDelegate().persistentContainer.newBackgroundContext()

    您可能想要的是这样的东西,您可以通过UIApplication.shared 单例访问AppDelegate 的同一实例:

    var container = (UIApplication.shared.delegate as?AppDelegate)?.persistentContainer var mainContext = (UIApplication.shared.delegate as?AppDelegate)?.persistentContainer.viewContext var backGroundContext = (UIApplication.shared.delegate as?AppDelegate)?.persistentContainer.newBackgroundContext()

    或者,简化一下:

    扩展 AppDelegate { static let shared = UIApplication.shared.delegate as!应用委托 } 类 CoreDataUtil { 静态让共享 = CoreDataUtil() var container = AppDelegate.shared.persistentContainer var mainContext = AppDelegate.shared.persistentContainer.viewContext var backGroundContext = AppDelegate.shared.persistentContainer.newBackgroundContext() // ... }

    【讨论】:

    • 是的,我已经尝试过了,但是这种方法有问题....检查我的编辑
    猜你喜欢
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    相关资源
    最近更新 更多