我在之前接受的答案中搜索了类似的错误消息,但他们建议的是在将任何行插入UITableView之前正确更新数据源(我想我已经在做了)。我使用UIRefreshControl(refreshControl)来刷新我的UITableView(myTable)。并且numberOfRowsInSection返回table(mainArray)的数据数组的长度。虽然我似乎在开始向我的表插入行之前更新了我的数组数据,但是应用程序在[self.myTable endUpdates]中崩溃;行给我以下错误消息:
由于未捕获的异常终止应用程序' NSInternalInconsistencyException',原因:'无效更新:第0部分中的无效行数。更新后现有部分中包含的行数(15)必须等于更新前的该部分中包含的行数(10),加上或减去从该部分插入或删除的行数(插入1个,删除0个),加上或减去移入的行数或者超出该部分(0移入,0移出)。'
这是我的代码:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return mainArray.count;
}
- (void)refresh:(UIRefreshControl *)refreshControl {
dispatch_queue_t checkQueue = dispatch_queue_create("pull to refresh queue",NULL);
dispatch_queue_t main = dispatch_get_main_queue();
dispatch_async(checkQueue, ^{
NSError *error;
jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://someurlwithjsondata.json"]];
if(jsonData != nil)
{
newData = [NSJSONSerialization
JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
if (error)
{
[refreshControl endRefreshing];
}
else
{
NSArray *indexPathArray = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:mainArray.count-1 inSection:0], nil];
NSMutableArray *values = newData[@"values"];
for (NSMutableDictionary *value in values)
{
[mainArray addObject:value];
}
dispatch_async(main, ^{
[self.myTable beginUpdates];
[self.myTable insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationTop];
[self.myTable endUpdates];
[refreshControl endRefreshing];
});
}
}
else
{
[refreshControl endRefreshing];
}
});
}
答案 0 :(得分:0)
问题很简单。当您重新加载表格时,您要向mainArray
添加5个对象,但只能通过insertRowsAtIndexPaths:
在表格视图中插入一行。这些需要匹配。插入与mainArray
一样多的行。
答案 1 :(得分:0)
您的代码非常容易出错,因为您手动添加行。您也在自己编写异步代码。一个更好的方法是使用AFNetworking的成功块填充' mainArray'并重新加载表而不是您编写的所有代码。它看起来像这样:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
///set mainArray
[self.myTable beginUpdates];
[self.myTable endUpdates];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];