1

这是与块的调用:

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

在接收方法的.h中:

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

在 .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.");
}

我的问题是为什么执行没有到达调用中传递的块openVacationWithName:?我从来没有见过写的 NSLog。

我怀疑这openVacationWithName:还没有完成,但是“退出助手”的 NSLog。确实打印。任何指导表示赞赏。仅供参考,这是用于 iTunes U/Stanford CS193P 作业 #6。

4

1 回答 1

2

你不是completionBlock在里面打电话openVacationWithName:usingBlock:。也许您想在方法结束时执行此操作:

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

  NSLog(@"Exiting helper.");
}

(在这种情况下,也许只返回 更有意义UIManagedDocument

或者也许completionHandler在方法中的那些 sopenWithCompletionHandler: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 回答