2013-12-23 51 views
-1

我了解块对象是如何工作的 - 但我还没有碰到过这种类型的块对象的到来,林不知道下面的代码做什么:块对象需要进一步解释

[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) { 
     if (!error) { 
      int i = 0; 
      do { 
       MKMapItem *mapItem = [response.mapItems objectAtIndex:i]; 
       [self.mapItems addObject:mapItem]; 
       i++; 
      } while (i < response.mapItems.count); 
      [[NSNotificationCenter defaultCenter] postNotificationName:@"Address Found" object:self]; 
     } else { 
      [[NSNotificationCenter defaultCenter] postNotificationName:@"Not Found" object:self]; 
     } 
    }]; 
} 

我将是巨大的,如果有人能提供关于这里发生了什么的解释。

+2

如果你“了解块对象是如何工作的”,那么你究竟在这里不了解什么? –

回答

0

您需要牢记有两种不同的技术块和通知。 当搜索完成后,在搜索数据被处理并通过NSNotification发送后调用块startWithCompletionHandler

您可以订阅在您的应用程序的任何位置接收通知。

了解更多关于 NSNotification Class Reference

0

块在ObjC只是一个回调函数。

在上面的函数localSearch.startWithCompletionHandler中,回调接受两个参数:响应和错误。

当调用该块时,当搜索完成时,上面的代码遍历'response'中的所有键/值对,并将它们添加到名为self.mapItems的本地键/值映射中。

之后它通过NSNotificationCenter通过“找到地址”发布通知。

如果错误不是NULL,即提供了一个指向NSError的指针,它只会发送一条错误通知消息。

希望这会有所帮助。

1

插入符号(^)后的函数是一个“块”。 See this post.

localSearch对象将在需要时(当它完成时)调用下面定义的块(匿名函数)。这就像分配给操作结果的委托一样,但不需要你定义一个新的函数来接收回调。调用类是委托(即self指函数中的调用者)。

我为特定细节添加了一些注释。

(MKLocalSearchResponse *response, NSError *error) { 
// If there is not an error 
     if (!error) { 
      int i = 0; 
      do { 
       MKMapItem *mapItem = [response.mapItems objectAtIndex:i]; 
// The map items found are added to a mapItems NSMutableArray (presumed) that is 
// owned by the original caller of this function. 
       [self.mapItems addObject:mapItem]; 
       i++; 
      } while (i < response.mapItems.count); 
// Using the Observer design pattern here. Some other object must register for the 
// @"Address Found" message. If any were found, it will be called. 
      [[NSNotificationCenter defaultCenter] postNotificationName:@"Address Found" object:self]; 
     } else { 
// Using the notification center to announce "not found". I am not sure if this is correct, 
// since this would be the response if there was an error, and not found is not necessarily 
// the same as an error occurring. 
      [[NSNotificationCenter defaultCenter] postNotificationName:@"Not Found" object:self]; 
     } 

对您有帮助吗?

有没有一个特定的问题,你试图解决?该方法完成后

+0

令人困惑的部分是这里所做的插入符号是什么:startWithCompletionHandler:^(MKLocalSearchResponse *响应,NSError *错误) – user3080344

+0

阅读帖子引用。它详细介绍了符号。它起初让我感到很开心......我对代表们很满意。 – FuzzyBunnySlippers

0

该块将被运行(startWithCompletionHandler:) 它检查是否没有错误,它会通过do while环列举response.mapItems阵列。它获取每个MKMapItem对象并将其添加到self.mapItems数组。所有数组完成后,会发布通知(Address Found),以便通知订阅它的每个对象。如果出现错误,则会发布通知(未找到)。