这是使用块的调用:
[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。
答案 0 :(得分:2)
您没有在completionBlock
内拨打openVacationWithName:usingBlock:
。也许你想在方法结束时这样做:
...
if (completionBlock) {
completionBlock(vacationDocument);
}
NSLog(@"Exiting helper.");
}
(在这种情况下,或许返回UIManagedDocument
)
或者可能在方法completionHandler
和openWithCompletionHandler:
中的saveToUrl:forSaveOperation:completionHandler:
内:
... ^(BOOL success) {
if (success) {
NSLog(@"Document was created.");
}
else {
NSLog(@"Couldn't create document at %@", url);
}
if (completionBlock) {
completionBlock(vacationDocument);
}
} ...