Search code examples
iosiclouduidocument

Does UIDocumentSaveForCreating close the document after creation?


What is the behavior of [UIDocument saveToURL:forSaveOperation:completionHandler:] when invoked with UIDocumentSaveForCreating?


Approach#1 - saveToURL: closes the document after save

Then no need to close the document.

MYDocument *document = [[MYDocument alloc] initWithFileURL:fileURL];
[document saveToURL:fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL saveSuccess) {
    if (!saveSuccess) {
        ALog(@"Failed to create file at %@", fileURL);
        failureBlock();
        return;
    }
    successBlock(fileURL);
}];

Approach#2 - saveToURL: does not close the document after save

Then I would have to close the document myself, like this:

MYDocument *document = [[MYDocument alloc] initWithFileURL:fileURL];
[document saveToURL:fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL saveSuccess) {
    if (!saveSuccess) {
        ALog(@"Failed to create file at %@", fileURL);
        failureBlock();
        return;
    }
    [document closeWithCompletionHandler:^(BOOL closeSuccess) {
        if(!closeSuccess) {
            ALog(@"Error during close after creating %@", fileURL);
            failureBlock();
            return;
        }
        successBlock(fileURL);
    }];
}];

Solution

  • Aha realized that UIDocument has a documentState property.

    In step1 the documentState returns UIDocumentStateNormal, so it is open.

    In step2 the documentState returns UIDocumentStateClosed, so it is closed.

    MYDocument *document = [[MYDocument alloc] initWithFileURL:fileURL];
    [document saveToURL:fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL saveSuccess) {
        if (!saveSuccess) {
            NSLog(@"Failed to create file at %@", fileURL);
            failureBlock();
            return;
        }
        NSLog(@"step1: documentState: %d", document.documentState);
        [document closeWithCompletionHandler:^(BOOL closeSuccess) {
            if(!closeSuccess) {
                NSLog(@"Error during close after creating %@", fileURL);
                failureBlock();
                return;
            }
            NSLog(@"step2: documentState: %d", document.documentState);
            successBlock(fileURL);
        }];
    }];
    

    So NO is the answer my own question

    Does UIDocumentSaveForCreating close the document after creation?