UIDocument, NSFileWrapper, and Images

I have a UIDocument that I would like to consist of (1) a txt file and (2) several jpg images. I put txt and all jpg in NSFileWrapper.

When I load a UIDocument, I need the information in the txt file very quickly, so first I load it and ignore all the images until they need them.

While I can lazily upload images, I’m not sure how to β€œlazily” save images (especially when using iCloud, I don’t want the files to be overloaded / downloaded). Suppose I downloaded all the images and did not change them. Then I want to save the UIDocument, ignoring all the images (since they have not changed), but you want to save the text as it changed.

How can i achieve this? Is it possible? Or is it automatically done? Or do I not want to put images in my UIDocument and allow each image to be processed by a different UIDocument? . All this confuses me a little, I'm afraid.

Here is my code that will save all the images and text (regardless of whether they were changed or not):


UIDocument

-(id)contentsForType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {

        NSMutableDictionary *wrappers = [NSMutableDictionary dictionary];
// the following puts a wrapper into a dictionary of wrappers:
        [self encodeObject:self.text toWrappers:wrappers toFileName:@"text.data"];
        [self encodeObject:self.photos toWrappers:wrappers toFileName:@"photos.data"];
        NSFileWrapper *fileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:wrappers];

        return fileWrapper;

    }

When I want to save a UIDocument:

[self.doc saveToURL:self.doc.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success) {
    [self.doc closeWithCompletionHandler:^(BOOL success) {}];
}];
+5
source share
1 answer

You must store the link to your NSFileWrapper in your UIDocument instance. This way, only the changed content will be overwritten, not the whole wrapper.

So, keep the link when downloading the file (or create a new one for new documents):

- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError {
    // save wrapper:
    self.fileWrapper = (NSFileWrapper*)contents;

now you only need to update the shell if the file has really changed:

- (id)contentsForType:(NSString *)typeName error:(NSError **)outError {
    NSFileWrapper *subwrapper = [self.fileWrapper.wrappers objectForKey:@"subwrapper"];
    if(self.somethingChanged) {
        [self.fileWrapper.wrappers removeFileWrapper:subwrapper];
        subwrapper = [[NSFileWrapper alloc] initRegularFileWithContents:…

, , , .

+3

All Articles