karelia / BSManagedDocument

Brings UIManagedDocument's design to OS X
Other
55 stars 25 forks source link

Copying files to the package #23

Closed colasbd closed 8 years ago

colasbd commented 10 years ago

Hi Mike !

I am having difficulties to understand how to copy files into the package. In my app, the user can select files (images, etc.) from an NSOpenPanel. These files will be attached to the document.

Right now, what I do is that I copy these files to a folder attached to the current document (via a UUID for the doc) which is in the Application Support folder.

I would like to use the package feature of BSManagedDocument but I wonder if it is easy/a good idea. Indeed, the additional data to the store consist only of files. I don't need to "see" these files in my application, I just use NSFileManager to copy them at the right place (and then execute some scripts on them, with NSTask).

The best would be to have as many "additional URLs" as there are attached files, but that would mean to override - (id)additionalContentForURL:(NSURL *)absoluteURL saveOperation:(NSSaveOperationType)saveOperation error:(NSError **)error; on run time, to make this method recognize any new attached file.

Seems too complicated...

If you have some time and if you can give me some help, thank you. If not, thank you also !

mikeabdullah commented 10 years ago

BSManagedDocument leaves this aspect almost entirely up to you to handle.

-writeAdditionalContent… gets called as part of the save process when it's time to touch the disk. -additionalContent… gets called on the main thread before that as a convenient way for you to pass data from the main thread through to the background.

Probably your simplest option is to maintain an NSFileWrapper directory containing all the files desired to be in the document. In -writeAdditionalContent… you write that wrapper out to disk, atomically. This will add in any new files, and delete any old ones.

colasbd commented 10 years ago

It's working, it was what I was looking for! Thank you!

colasbd commented 10 years ago

I have some problems with the NSFileWrapper class. It works well with atomic option but it seems more logical not to re-write always all the content of the wrapper (which will ultimately have hundreds of files).

If you can see this SO question, maybe you could help. Thanks ;-)

mikeabdullah commented 10 years ago

Atomic writing is likely what you want here. Unlike NSDocument, BSManagedDocument doesn't provide atomic writing for you (Core Data itself provides atomic writes; everything else must cope around that).

Read up a bit more on NSFileWrapper; when possible, writes are optimised to use hard links for speed, rather than writing entire copies of all the files.