2013-06-05 51 views
0

我正在嘗試使用AFJSONRequestOperation來從JSON提要中獲得數據的安寧。AFJSONRequestOperation不更新塊以外的內容

下面的代碼拉得很好,當打印stringURL時,它會打印正確的url。但是,我嘗試了幾種不同的方式將url分配給塊之外的新變量。無論我是否嘗試將生成的url分配給另一個全局NSURL(確保使用__block)或嘗試將其添加到數組,它似乎不會及時更新以在NSLog中打印出來。我懷疑這是因爲手術尚未完成。我在致電NSLog([streamUrls objectAtIndex:0]);之前如何確保操作已完成?

這是我使用的代碼。

NSURL *url = [contentUrls objectAtIndex:indexPath.row]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSONSound) { 

    NSString *stringURL = [NSString stringWithFormat:@"%@", 
          JSONSound[@"stream_url"], nil]; 

    NSURL *streamURL = [NSURL URLWithString:stringURL]; 
    NSLog(stringURL); 
    [streamUrls addObject:streamURL]; 
    [self.collectionView reloadData]; 
} failure:nil]; 
[operation start]; 

NSLog([streamUrls objectAtIndex:0]); 

編輯:[self.collectionView reloadData];這條線似乎沒有影響的情況。

回答

3

爲了確保操作已使得代碼做任何調用之前完成,你可以使用AFJSONRequestOperation,這是你一直在做什麼,當你添加對象的streamUrls成功塊:

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSONSound) { 
    NSString *stringURL = [NSString stringWithFormat:@"%@", 
         JSONSound[@"stream_url"], nil]; 

    NSURL *streamURL = [NSURL URLWithString:stringURL]; 
    NSLog(stringURL); 
    [streamUrls addObject:streamURL]; 
    [self.collectionView reloadData]; 
    NSLog([streamUrls objectAtIndex:0]); 
} failure:nil]; 

reloadData不會影響數據源。它只是刷新基於數據源顯示的收集視圖(數據源是否更新)。