2017-09-02 51 views
0

我有一個tableview,我試圖用數據填充。我將值賦給函數中的數組。一切都保存起來,直到它離開searchWithLocation函數。看着日誌,它讓我覺得它與訂購有關,就像我沒有足夠快地填充我的數據一樣。或者這可能不是原因,我真的不知道。NSMutable陣列退出功能後不保留數據

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    venueName = [[NSMutableArray alloc] init]; 

    [YLPClient authorizeWithAppId:@"sdgsfgfgfg" 
          secret:@"aegsgdgdfs" 
       completionHandler:^ 
    (YLPClient *client, NSError *error) { 
     // Save your newly authorized client 
     self.client = client; 

     [self.client searchWithLocation:@"Chicago" 
         completionHandler:^ 
      (YLPSearch *search, NSError *error) { 
       for (YLPBusiness *business in search.businesses) { 
        [venueName addObject:business.name]; 
       } 
       NSLog(@"I return results: %lu", (unsigned long)[venueName count]); 
      }]; 
     NSLog(@"I return 0: %lu", (unsigned long)[venueName count]); 
    }]; 
} 

... 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    NSLog(@"number of rows in section: %lu", (unsigned long)[venueName count]); 
    return [venueName count]; 
} 

日誌:

2017-09-02 14:46:39.708 whatever[67890:8535793] number of rows in section: 0 
2017-09-02 14:46:39.714 whatever[67890:8535793] number of rows in section: 0 
2017-09-02 14:46:39.715 whatever[67890:8535793] number of rows in section: 0 
2017-09-02 14:46:40.448 whatever[67890:8535846] I return 0: 0 
2017-09-02 14:46:41.174 whatever[67890:8535846] I return results: 20 

回答

1

你有異步執行程序的一種誤解。每個完成處理程序可以在「調用」執行路徑已經終止後執行。在你的情況下:

[self.client searchWithLocation:@"Chicago" 
       completionHandler: 
    // This completion handler can be executed after seconds, minutes or even hours. 
    ^(YLPSearch *search, NSError *error) 
    { 
    NSLog(@"As times go by – sometime in the future"); 
    for (YLPBusiness *business in search.businesses) 
    { 
     [venueName addObject:business.name]; 
    } 
    NSLog(@"I return results: %lu", (unsigned long)[venueName count]); 
    }]; 
    // This path is executed immediately. esp. likely before the cmpletion handler is executed 
    NSLog(@"It is now or never"); 
    NSLog(@"I return 0: %lu", (unsigned long)[venueName count]); 

把代碼移到裏面的完成處理器後面。

+0

所以如果我想更新我的tableViewCells,我需要等到completionHandler觸發並調用一些更新方法嗎?對不起,如果我想要做的沒有道理,我來自網絡背景。 – itsclarke

+0

啊,好吧,我很酷,我知道了,我只是在回顧你所說的內容後才說出來。非常感謝。 – itsclarke