处理核心数据的临时NSManagedObjectID

时间:2016-08-07 06:01:12

标签: core-data nsmanagedobjectcontext nsmanagedobjectid

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

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

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

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

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

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

我怎样才能实现这一目标?感谢。

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

0 个答案:

没有答案