macoscocoalazy-loadingnsdocumentnsfilewrapper

Does NSFileWrapper support lazy loading?


I am creating a NSDocument package that contains potentially hundreds of large files, so I don't want to read it all in when opening the document.

I've spent some time searching, but I can't find a definitve answer. Most people seem to think that NSFileWrapper loads all of the data into memory, but some indicate that it doesn't load data until you invoke -regularFileContents on a wrapper. (See Does NSFileWrapper load everything into memory? and Objective-C / Cocoa: Uploading Images, Working Memory, And Storage for examples.)

The documentation isn't entirely clear, but options like NSFileWrapperReadingImmediate and NSFileWrapperReadingWithoutMapping seem to suggest that it doesn't always read everything in.

I gather that NSFileWrapper supports incremental saving, only writing out sub-wrappers that have been replaced. So it'd be nice if it supports incremental loading too.

Is there a definitive answer?


Solution

  • NSFileWrapper loads lazily by default, unless you specify the NSFileWrapperReadingImmediate option. It will avoid reading a file into memory until something actually requests it.

    As a debugging aid only, you can see whether a file has been loaded yet, by examining:

    [wrapper valueForKey:@"_contents"];
    

    It gets filled in as NSData once the file is read from disk.