2013-12-23 53 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),以便通知訂閱它的每個對象。如果出現錯誤,則會發布通知(未找到)。