2013-01-23 74 views
0

我注意到一些非常奇怪的行爲,我希望看看是否有其他人遇到過這種情況。我正在進行異步API調用(代碼如下)。當調用完成後,從調用結果中填充一個數組,然後重新加載我的表(這應該會導致調用cellForRowAtIndexPath),該表應該使用我的數組數據更新我的表視圖。然而,tableview中的數據在它需要從其他方式重新加載時纔會出現 - 例如,如果我通過單擊選項卡然後返回到原始視圖來更改視圖。看起來有一些「刷新表」的方面,但我在異步調用返回時調用reloadData異步調用不刷新表

代碼:

-(void)refreshWeeksOffers 
{ 
    [array removeAllObjects]; 

    NSMutableURLRequest *request = 
     [WebRequests createPostRequestWithApiCall:@"getResults" bodyData:@"params={\"locale\" : \"US\"}"]; 

    [NSURLConnection 
    sendAsynchronousRequest:request 
    queue:[[NSOperationQueue alloc] init] 
    completionHandler:^(NSURLResponse *response, 
         NSData *data, 
         NSError *error) 
    { 
     if ([data length] >0 && error == nil) 
     { 
      // parse home page offers from resulting json 
      JsonParser *parser = [[JsonParser alloc] initWithData:data]; 
      array = [parser parseHomepageResults]; 

      [self.topWeekTable reloadData]; 

     } 
     else if ([data length] == 0 && error == nil) 
     { 
      NSLog(@"Nothing was downloaded."); 
     } 
     else if (error != nil){ 
      NSLog(@"Error = %@", error); 
     } 

    }]; 

    [self.topWeekTable reloadData]; 
} 

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [array count]; 
} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

    if(!cell) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
    } 

    Offer *currentOffer = (Offer *)[array objectAtIndex:indexPath.row]; 

    cell.textLabel.text = [NSString stringWithFormat:@"%.1f%% Back", currentOffer.advertisedRate]; 

    NSData *data = [NSData dataWithContentsOfURL:currentOffer.storeImage]; 
    UIImage *img = [[UIImage alloc] initWithData:data]; 

    cell.imageView.image = img; 

    return cell; 
} 

回答

1

這是因爲你是從後臺線程,不支持調用的UIKit。

試試這個:

[ self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO ] ; 

另一種策略,我寧願是這樣的:

-(void)startAsyncSomething 
{ 
    [ obj operationWithAsyncHandler:^{ 
     [ [ NSThread mainThread ] performBlock:^{ 
      ... handle completion here ... 
     } ] 
    }] 
} 

您可以添加-performBlock:NSThread與類別是這樣的:

@implementation NSThread (BlockPerforming) 

-(void)performBlock:(void(^)())block 
{ 
    if (!block) { return ; } 
    [ self performSelector:@selector(performBlock:) onThread:self withObject:[ block copy ] waitUntilDone:NO ] ; 
} 

@end 
+0

謝謝,那就是訣竅! –

+0

第一種解決方案讓人煩惱於更復雜的情況,所以我更喜歡第二個作爲編輯添加的東西。 – nielsbot