Insert a PDF file into Core Data?

2019-01-28 23:41发布

问题:

I'm using my app to import some PDF files. But I'm trying to insert my PDF file int my database. I'm using Core Data. Is it possible to do this ? If it is, how can I do it ? Which kind of types I have to use (NSData, NSDocument, ... ?)

Thanks you so much! :)

回答1:

To store a PDF (or really any big data blob):

  1. Use the Core Data "binary" type for the attribute, which corresponds to NSData.
  2. In your Core Data model, turn on "Allows External Storage" for the attribute so that Core Data can store the data outside of the persistent store.

It's often better to just write the PDF to a file, and store the filename in your persistent store instead of the whole file.



回答2:

Usually for large files, i.e large images or pdf files, what you should save in core data is simply a reference to the file, and store the pdf in NSCachesDirectory or in a permanent directory, depending on your needs.

Hope that helps.