Add images in NSAttributedString and save to Core Data peformance

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-07 02:57:08

问题


I'm encountering this huge performance issue while saving the NSAttrbutedString with images in it to Core Data.

There is a UITextView where allows the user to input text as well as adding images. When user finishes typing and click 'done' button, it will be saved to CoreData, and shows in a TableView.

Here is how I save the content when click 'done' button:

Create a private MOC and assign the AppDelegates managedObjectContext as its parent MOC.

privateMOC = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateMOC.parent = managedObjectContext

privateMOC.perform {
    do {
      try self.privateMOC.save()

      self.managedObjectContext.performAndWait {
        do {
          try self.managedObjectContext.save()
        } catch {
          fatalError("Failure to save context: \(error)")
        }
      }
    } catch {
      print("Could not save \(error)")
    }
  }

There are two issues:

  1. Depends on the images, when I click 'done' button, the UI is blocked and takes 3 - 5 seconds before the view dismissed and shown in the TableView.

  2. I check the actual database .sqlite and found, one single newly-added entry(text and images in UITextView) makes the database size increases almost 12MB! (Maybe the images take too much space?)

Any suggestions how to tackle these issues? Thanks!


回答1:


These issues are going to be difficult to prevent in your use case. By using NSCoding on an NSAttributedString that includes images, what you're asking for is a binary blob where you can't control the encoding process in any way.

  • It might be that the image size is inflated, e.g. because you're saving the uncompressed data instead of a PNG or JPEG. But you can't do anything about that because you can't control how NSAttributedString handles it. So you're probably stuck with the large data size.
  • The long processing time is probably connected to the previous point-- you can't control what NSAttributedString is doing internally, but it's likely that a lot of that time is taken up dealing with the image(s).

You might improve on the save time if you encoded the attributed strings on your own instead of using a transformable attribute. Then you could start the encoding in advance, in the background, instead of having it happen when you're saving data. You probably can't fix the encoding time, but you may be able to make it happen earlier and be less noticeable. I think you're stuck with the size as long as you're using encoded attributed strings, though.

I don't know what your app is doing but if you could get away from potentially massive NSAttributedStrings you'll avoid the problems you're having.



来源:https://stackoverflow.com/questions/43454065/add-images-in-nsattributedstring-and-save-to-core-data-peformance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!