插入方法调用插入

我正在阅读本教程,并遇到了难倒我的这一行代码:

[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]; } }]; 

我不明白的部分如下: ^(MKLocalSearchResponse *response, NSError *error) {

这个插入符号^以及之后发生的事情是我不知道的。

我查看了一些文档,但找不到任何东西。

^表示目标c中的一个 。 它就像一个匿名函数,可以被分配给一个variables或作为parameter passing给一个函数,如你的例子所见。 阅读更多的苹果文档:

https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/Blocks/Articles/00_Introduction.html

定义一个块:

  ^{ NSLog(@"This is a block"); } 

将一个块分配给一个variables:

 void (^simpleBlock)(void); // or simpleBlock = ^{ NSLog(@"This is a block"); }; 

调用一个块:

 simpleBlock(); 

使用块作为消息的参数:

 - (IBAction)fetchRemoteInformation:(id)sender { [self showProgressIndicator]; XYZWebTask *task = ... [task beginTaskWithCallbackBlock:^{ [self hideProgressIndicator]; }]; } 

从Apple文档中获取示例

^表示一个 – 一组可以像variables一样传递的代码。

在你的例子中:

 ^(MKLocalSearchResponse *response, NSError *error) { ... } |---------------------------------------------| |---| Arguments (you can use these in the block) ^ Code goes here 

由于您正在使用完成处理程序,您的块不返回任何东西给它的调用者。 当MapKitsearch完成search时,它会调用该块中的所有代码。

苹果在这方面有一个很好的文件。