2011-10-17 30 views
1

我正在調用一個方法,在視圖加載時選擇表視圖的第一行。但由於某種原因,在撥打selectFirstRow之後,它會回到self.couldNotLoadData = NO並繼續往返。任何想法爲什麼?當最初的if/else循環轉到else時,該方法不會被調用,因此它不會循環。爲什麼我用我的UITableView無限循環?

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section 
{ 
    if (self.ichronoAppointments.count > 0) 
    { 
     self.couldNotLoadData = NO; 
     [self selectFirstRow]; 
     return self.ichronoAppointments.count; 
    } 
    else 
    { 
     self.couldNotLoadData = YES; 
     return 1; 
    } 
} 
-(void)selectFirstRow 
{ 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop]; 
} 

回答

1

這是未經證實的,但我敢打賭,當你從selectFirstRow調用selectRowAtIndexPath:animated:scrollPosition:它調用UITableView的委託的-tableView:numberOfRowsInSection:

基本上,你已經有了無限的遞歸。 tableView:numberOfRowsInSection調用selectFirstRow,其調用selectRowAtIndexPath:animated:scrollPosition:,其調用tableView:numberOfRowsInSection無限。

您需要將您的selectFirstRow電話轉至viewDidAppearviewWillAppeartableView:numberOfRowsInSection:是沒有地方做任何複雜的事情......它被稱爲非常經常。

而當你在它的時候,將檢查項目數量的邏輯移動到selectFirstRow。即

if (self.ichronoAppointments.count) { 
    //select the first row 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop]; 
} else { 
    //don't 
    NSLog(@"Couldn't select first row. Maybe the data is not yet loaded?"); 
} 

它更幹/模塊化/清潔劑的方式。