2013-08-06 46 views
0

我正在使用标准方法通过AFNetworking获取和解析JSON,然后将数据用于填充表视图。重新加载表视图数据,现有数据可见

NSURL *url = [NSURL URLWithString:serverURL]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

AFJSONRequestOperation *operation = [AFJSONRequestOperation 
            JSONRequestOperationWithRequest:request 
            success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) { 
             [refresh endRefreshing]; 
             self.results = [json valueForKeyPath:@"data"]; 
             [self.tableView reloadData]; 
            } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
             [refresh endRefreshing]; 
            }]; 
[self.tableView reloadData]; 
[operation start]; 

它是这样的,每一个使用者拉动刷新整个表视图时间消失,并且新数据被加载,然后呈现给用户,后一秒钟左右。不过,我希望表中的数据保持在那里,直到新数据可用并加载。因此,我认为[self.tableView reloadData];认为它可以使其工作,同时明显地和前几秒钟它可以工作,但是应用程序很快就会崩溃。随着错误:

Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayI objectAtIndex:]: index 1 beyond bounds for empty array'

现在我也不完全肯定这是去这样做,所以基本上是正确的方法,我的问题是如何将保持数据表视图,直到新的数据加载,或将现有数据向下推送到表格视图中,有点像Facebook和Twitter应用在刷新新闻供稿/时间表时所做的那样。

UPDATE

这个方法我试过:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.results count] inSection:0]; 
NSArray *indexArray = [NSArray arrayWithObjects:indexPath, nil]; 
[self.tableView insertRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic]; 

,但我得到了以下错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert row 15 into section 0, but there are only 15 rows in section 0 after the update'

回答

0

在你的成功块,你必须首先检查你是否得到数据。如果有任何数据,然后重新加载您的tableview与新的数据,否则你不应该尝试改变现有的数据。尝试这个。

NSArray *tempResults = [json valueForKeyPath:@"data"]; 
    if(tempResults && [tempResults count] > 0) 
    {            
     self.results = tempResults;           
    }           
    [self.tableView reloadData]; 

在tempResults上保留一个断点,看看你得到了什么数据。

+0

感谢您的回答,但那并没有真正回答这个问题。我试图在现有数据之上添加新数据,而不是简单地使用新数据重新加载表。 –