1

Here is the call with the block:

[VacationHelper openVacationWithName:vacationName
                usingBlock:^(UIManagedDocument *vacationDocument) {
   NSLog(@"vacationDocument.description:%@", vacationDocument.description);
}];

In the receiving method's .h:

typedef void (^completion_block_t)(UIManagedDocument *vacationDocument);

And in the .m:

+ (void)openVacationWithName:(NSString *)vacationName
                  usingBlock:(completion_block_t)completionBlock;
{
    NSLog(@"Opening Vacation Document");

    // Get documents directory and path.
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url        = [url URLByAppendingPathComponent:vacationName];

    // Create the document and open if a match exists on file.
    UIManagedDocument *vacationDocument = [[UIManagedDocument alloc] initWithFileURL:url];
    if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]]) {
        NSLog(@"vacationDocument.documentState:%i", vacationDocument.documentState);
        [vacationDocument openWithCompletionHandler:^(BOOL success) {
            if (success) NSLog(@"Document was opened.");
            else NSLog (@"Couldn't open document at %@", url);
        }];
    } else {

        // No match exists, so save the document to file.
        [vacationDocument saveToURL:url forSaveOperation:UIDocumentSaveForCreating
                  completionHandler:^(BOOL success) {
                      if (success) NSLog(@"Document was created.");
                      else NSLog(@"Couldn't create document at %@", url);
                  }];
    }
    NSLog(@"Exiting helper.");
}

My question is why does execution not reach the block passed in the call to openVacationWithName:? I never see the NSLog written.

I suspect that openVacationWithName: doesn't finish, but the NSLog for "Exiting helper." does print. Any guidance appreciated. FYI this is for iTunes U/Stanford CS193P assignment #6.

4

1 に答える 1

2

あなたはcompletionBlockの中で呼んでいませんopenVacationWithName:usingBlock:。メソッドの最後でそれをやりたいと思うかもしれません:

  ...
  if (completionBlock) {
    completionBlock(vacationDocument);
  }

  NSLog(@"Exiting helper.");
}

(この場合、単に を返す方が理にかなっているかもしれませんUIManagedDocument)

あるいは、これらcompletionHandlerの s 内のメソッドopenWithCompletionHandler:saveToUrl:forSaveOperation:completionHandler::

... ^(BOOL success) {
  if (success) {
    NSLog(@"Document was created.");
  }
  else {
    NSLog(@"Couldn't create document at %@", url);
  }

  if (completionBlock) {
    completionBlock(vacationDocument);
  }
} ...
于 2012-06-03T20:47:10.810 に答える