gpt4 book ai didi

objective-c - 完成 block 不执行

转载 作者:行者123 更新时间:2023-11-29 11:12:38 25 4
gpt4 key购买 nike

这是 block 的调用:

[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: 时传递的 block ?我从来没有看到写过 NSLog。

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

最佳答案

你没有调用 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);
}
} ...

关于objective-c - 完成 block 不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10873776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com