proxi
proxi

Reputation: 1263

UIDocument closeWithCompletionHandler: completes immediately

Documentation of closeWithCompletionHandler" says: "After the save operation concludes, the code in completionHandler is executed." However, in my app this code:

NSLog(@"closeWithCompletionHandler");
[self.document closeWithCompletionHandler:^(BOOL success) {
    if (success) {
        NSLog(@"completionHandler");
...

executes immediately (on iOS6.1):

2013-07-18 19:43:12.673 FooBar[819:907] closeWithCompletionHandler
2013-07-18 19:43:12.675 FooBar[819:907] completionHandler <-- look here
2013-07-18 19:43:16.234 FooBar[819:907] encoded

even though actual writing data to a file takes several seconds (I know that by tracking contentsForType:error:).

contentsForType:error: implementation looks like this:

- (id)contentsForType:(NSString *)typeName error:(NSError *__autoreleasing *)outError
{
    NSMutableDictionary* wrappers = [NSMutableDictionary dictionary];
    [self encodeObject:self.data toWrappers:wrappers preferredFilename:kDocumentDataPath];
    NSFileWrapper* fileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:wrappers];

    NSLog("encoded");

    return fileWrapper;
}

Please note encoding finishing long after completionHandler executes:

2013-07-18 19:43:12.675 FooBar[819:907] completionHandler
2013-07-18 19:43:16.234 FooBar[819:907] encoded <-- look here

Why is this so? How should I make sure that data is written out to file before proceeding?

Upvotes: 1

Views: 488

Answers (1)

Ben Coffman
Ben Coffman

Reputation: 1740

I believe you want to look for the value of success being true, so your code might look like such

"How should I make sure that data is written out to file before proceeding?"

completionHandler: A block with code to execute after the save-and-close operation concludes. The block returns no value and has one parameter: success YES if any save operation succeeds, otherwise NO.

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIDocument_Class/UIDocument/UIDocument.html#//apple_ref/occ/instm/UIDocument/closeWithCompletionHandler:

Answer:

NSLog(@"closeWithCompletionHandler");
[self.document closeWithCompletionHandler:^(BOOL success) {
     if(success){   
         NSLog(@"completionHandler");
     }

"Why is this so?"

Any number of reasons, one could be because the write failed and it's rolling back, another could be additonal OS overhead that iOS does. Last could be you are simply reading the length of time wrong.

Upvotes: 1

Related Questions