核心数据子上下文无法将更改推送到父上下文

时间:2016-07-09 18:55:43

标签: swift core-data

我的应用会检索一些JSON。我进行调度调用,检索主队列并使用父/主对象上下文将JSON数据插入到Core Data中。

检索到的JSON还包括图像地址。我将它的检索发送到后台队列,并且由于未保留父级,因此需要子管理对象上下文。下面的代码概述了我的图像检索。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
    guard let url = NSURL(string: json["KategoriResim"].stringValue) else { return }

    let privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
    privateManagedObjectContext.parentContext = CoreDataStack.sharedInstance.managedObjectContext

    NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
      guard let httpUrlResponse = response as? NSHTTPURLResponse where httpUrlResponse.statusCode == 200,
            let mimeType = response?.MIMEType where mimeType.hasPrefix("image"),
            let data = data where error == nil
        else {
          print("Problem downloading the image of the category with id: \(category.id) and name: \(category.title)")
          return
      }

      if let privateCategory = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: privateManagedObjectContext) as? Category {
        privateCategory.logo = data
      }

      if privateManagedObjectContext.hasChanges {
        do {
          try privateManagedObjectContext.save()
        } catch {
          print("An error occured while saving the child context: \(error)")
        }
      }
    }.resume()
}

即使子管理对象上下文的保存成功或者没有任何其他错误消息,子上下文也不会被推送到父级。

我错过了什么?

更新

在Martin R评论之后我的修改:

let privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateManagedObjectContext.parentContext = CoreDataStack.sharedInstance.managedObjectContext

CoreDataStack.sharedInstance.managedObjectContext.performBlock {
    guard let url = NSURL(string: json["KategoriResim"].stringValue) else { return }

    NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
        guard let httpUrlResponse = response as? NSHTTPURLResponse where httpUrlResponse.statusCode == 200,
            let mimeType = response?.MIMEType where mimeType.hasPrefix("image"),
            let data = data where error == nil
            else {
                print("Problem downloading the image of the category with id: \(category.id) and name: \(category.title)")
                return
        }

        if let privateCategory = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: privateManagedObjectContext) as? Category {
            privateCategory.logo = data
        }
    }.resume()
}

if privateManagedObjectContext.hasChanges {
    do {
        try privateManagedObjectContext.save()
    } catch {
        print("An error occured while saving the child context: \(error)")
    }
}

0 个答案:

没有答案