0

我正在尝试检索核心数据实体的对象 ID。

我有两个 Core Data 上下文:main(mainQueueConcurrency) 和 child(privateQueueConcurrency) - 我知道,这不是最好的解决方案,但我仍在学习 Core Data,所以希望我的下一个实现会更好。

无论如何,我的目标是将图像下载的磁盘位置分配给传递的实体。由于 NSURLSession 在不同的线程上工作,我的主要上下文消失了。因此,我使用子上下文。

虽然由于在检索对象 ID 时没有保存我的主要上下文,但它是临时的,因此我无法进行适当的插入。

我在获取对象 ID 之前调用了一些保存语句,但没有任何区别。

下面的代码概述了我的情况。我用注释简化了一些地方,因为它们与这种情况无关。

我怎样才能做到这一点?谢谢。

coreDataStack.managedObjectContext.performBlockAndWait{
  for result in jsonCategoriesArray {
    if let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: coreDataStack.managedObjectContext) as? Category {
      self.insertCategory(category, usingJSON: result, withDeletionFlag: false)
    }
  }
}



private func insertCategory(category: Category, usingJSON json: JSON, withDeletionFlag deletionFlag: Bool) {
  // Assign the text data from JSON into the entity

  do {
    print("Temporary Object ID: \(category.objectID.temporaryID)")
    print("Object ID: \(category.objectID)")
    let managedObject = try coreDataStack.managedObjectContext.existingObjectWithID(category.objectID) as? Category
  } catch {
    print(error)
  }

  // retrieve the image URL

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

  privateManagedObjectContext.performBlock {
    NSURLSession.sharedSession().dataTaskWithURL(categoryIconURL) { (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("ERROR: Problem downloading the category icon.")
          print(error)
          return
      }

      // determine where to save the images
      let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String

      // retrieve the image name from the image address
      let iconName = categoryIconAddress.componentsSeparatedByString("/").last!

      // prepare the path for the image to be saved
      let iconSaveDestinationPath = documentsPath.stringByAppendingString("/" + iconName)

      // write the image to the prepared path
      do {
        try UIImageJPEGRepresentation(UIImage(data: data)!, 1.0)?.writeToFile(iconSaveDestinationPath, options: .DataWritingAtomic)
      } catch {
        print("There was a problem writing the downloaded image to the disk.")
        print(error)
      }

      managedObject?.icon = iconSaveDestinationPath
    }.resume()

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

    coreDataStack.saveContext()
  }
}
4

0 回答 0