我不确定如何处理块。例如,在我的viewDidLoad中,我调用了一个函数“ useDocument”来设置Core Data。我希望一旦可以使用Core Data,就可以调用另一个函数来处理某些查询。就像ASIHTTPRequest一样,当客户端收到响应时,将调用一个函数来处理响应。
我猜想触发函数不是使用块的正确方法。但是正确的方法是什么?
- (void)useDocument
{
if (!self.database) {
self.database = [DataModelDocument sharedDocument];
}
if (![[NSFileManager defaultManager] fileExistsAtPath:[self.database.fileURL path]]) {
// does not exist on disk, so create it
[self.database saveToURL:self.database.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (!success) {
NSLog(@"database doesn't exist on disk, we fail to create it");
}
}];
} else if (self.database.documentState == UIDocumentStateClosed) {
// exists on disk, but we need to open it
[self.database openWithCompletionHandler:^(BOOL success) {
if (!success) {
NSLog(@"database exists on disk, but we fail to open it");
}
}];
} else if (self.database.documentState == UIDocumentStateNormal) {
// already open and ready to use
}
}
最佳答案
没有正确的方法来使用块,因为没有正确的方法来使用函数。
块是功能。不仅仅是一个功能,而且没有太多不同。因此,让我们暂时忘记这些差异。功能。
使用一个函数,您将编写类似
void callback (BOOL success) {
if (success) {
// do something useful
}
}
[database openWithCallback: &callback];
在这里有点不耐烦。 ish。
块允许您直接编写回调。
[self.database openWithCompletionHandler: ^(BOOL success) {
if (!success) {
// oops, handle that
}
}];
在那种特殊情况下,块不能解决功能无法解决的任何问题。他们甚至花费更多。
当您大量使用这些优点时,它们就会显示出来。如果您编写的操作是完全异步的,则可以以简化的方式编写代码。
伪代码:
dispatch block: ^(){
some heavy computation here
dispatch block: ^(){
computation done, update the UI or something
}
}
非常简单的例子。当然,使用函数编写此代码是完全可能的。但不那么可读。
现在想象您正在分派大量的块,您可以创建块组,然后在完全执行该组时执行一个块。很容易写,很容易阅读。这开始成为噩梦,到处都是函数指针。
而现在,是什么使块不仅仅是功能?
块是一种功能。随着上下文。块可以访问相同范围内的变量。在上面的简单示例中,工作块可以访问调用范围,而完成块可以访问调用范围和工作块范围。当然,这可以通过功能和结构来完成。有了很多代码,很难阅读。积木更优雅地解决了这一问题。
我建议您阅读有关中央中央调度的信息。这显然是区块展示其真正潜力和表现力的地方。
关于ios - 关于iOS区块的困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11093933/