NSDocument to hold a complete folder?
Asked Answered
P

1

9

I ask sorry if this argument has already been covered, but after some research i found nothing precise.

I need to make a document based application, where the document is actually not a single file but a structured collection of files, in a directory. The windows will show a pdf contained in the folder, with a specific filename, and enrich it with informations from the other files in the folder. I cannot use pdf annotations to achieve this, i really need to keep the files separated from the pdf.

What's the best approach to achieve this? All the sample code i found use a single file..

Phonemics answered 14/4, 2011 at 15:23 Comment(0)
S
13

You can use NSFileWrapper as a package directory in document-based applications.

In your application Info.plist file, state that your document type is a package or bundle (key LSTypeIsPackage with value YES).

In your NSDocument subclass, implement the following methods for reading and writing. In this example, I’m assuming the corresponding model instance variables are pdfData and signatureBitmapData, which are stored in the package directory under MainDocument.pdf and SignatureBitmap.png, respectively.

- (BOOL)readFromFileWrapper:(NSFileWrapper *)dirWrapper
                     ofType:(NSString *)typeName
                      error:(NSError **)outError
{

    NSFileWrapper *wrapper;
    NSData *data;

    wrapper = [[dirWrapper fileWrappers] objectForKey:@"MainDocument.pdf"];
    data = [wrapper regularFileContents];
    self.pdfData = data;

    wrapper = [[dirWrapper fileWrappers] objectForKey:@"SignatureBitmap.png"];
    data = [wrapper regularFileContents];
    self.signatureBitmapData = data;

    …

    return YES;
}

- (NSFileWrapper *)fileWrapperOfType:(NSString *)typeName
                               error:(NSError **)outError
{
    NSFileWrapper *dirWrapper = [[[NSFileWrapper alloc]
        initDirectoryWithFileWrappers:nil] autorelease];

    [dirWrapper addRegularFileWithContents:self.pdfData
        preferredFilename:@"MainDocument.pdf"];

    [dirWrapper addRegularFileWithContents:self.signatureBitmapData
        preferredFilename:@"SignatureBitmap.png"];

    …

    return dirWrapper;
}

From the user perspective, the package directory shows up in Finder as if it were a single file, much like Xcode .xcodeproj directories or application bundles.

Simonetta answered 15/4, 2011 at 10:47 Comment(3)
Thank you for the detailed answer, i'll try this immediatly.Phonemics
@Phonemics Cheers. Just one remark: I haven’t included error checking and reporting in my example, but you should do that in your production code.Simonetta
Would it be possible to open MainDocument.pdf without specifying LSTypeIsPackage and just save the document together with the image file using the NSFileWrapper API?Kaciekacy

© 2022 - 2024 — McMap. All rights reserved.