重新加载表崩溃应用程序
此代码导致应用程序崩溃!我正在循环查看字典,并且一切都很顺利。它的工作原理,当我在for循环而不是其他写-1,重新加载表崩溃应用程序
-(void)updateProjectTimes {
for(int i = 0; i < [projectsTable numberOfRowsInSection:0]-1; i++) {
NSString *currentValue = [[[projects objectForKey:@"activeProjects"] objectAtIndex:i] objectForKey:@"timepassed"];
NSString *finishValue = [[[projects objectForKey:@"activeProjects"] objectAtIndex:i] objectForKey:@"timeleft"];
if([currentValue intValue] < [finishValue intValue]) {
[[[projects objectForKey:@"activeProjects"] objectAtIndex:i] setObject:[NSString stringWithFormat:@"%d", ([currentValue intValue] + 1)] forKey:@"timepassed"];
} else {
[(NSMutableArray *)[projects objectForKey:@"activeProjects"] removeObjectAtIndex:i];
if([[projects objectForKey:@"activeProjects"] count] == 0) {
[projectTimer invalidate];
projectTimer = nil;
}
}
//[projectsTable reloadData]; works if i put it here!
}
[projectsTable reloadData]; //<- But not here!! :(
}
我假设你用tableView
工作呢。显然你正在修改你的tableView的数据源。当你从数据源中删除一个对象时,你也必须调整你的tableView。意思是致电reloadData
,或致电[tableView deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation]
。
如果您放置-1,应用程序不会崩溃的原因可能是 - 也许 - 因为只有与[currentValue intValue] < [finishValue intValue]
条件匹配的项目,所以如果您通过[projectsTable numberOfRowsInSection:0]-1
,删除该对象后, numberOfRowsInSection
与项目表的数量相匹配。
但是它只适用于一个周期。当下一个周期发生时,在if...loop
中,应用程序再次崩溃,除非在同一if...loop
中包含[projectsTable reloadData]
。
虽然reloadData
方法工作得很好,但如果你只是删除一排,或通过添加或删除对象,它能够更好地使用deleteRowsAtIndexPaths
或insertRowsAtIndexPaths
方法添加一行到你的餐桌。您的应用程序的开销和工作量会更少,并且会使其更平滑,更快速。
为了让您的代码正常工作,请在[(NSMutableArray *)[projects objectForKey:@"activeProjects"] removeObjectAtIndex:i];
之后通过调用deleteRowsAtIndexPaths
从您的tableView中删除相应的对象。您也可以使用beginUpdates
和endUpdates
。有关完整参考,请参阅http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html
希望它有帮助。
找到解决方案。问题是,如果一个对象使用currentValue == finishValue加载,它会立即从数组中移除,从而创建一个洞。假设我们从一开始就有五个对象,其中一个在for循环中被删除,但循环仍然认为我们有五个,所以它超越了:) 对不起,我的错误! – Hjalmar 2012-01-11 21:49:21
你的错误是什么? – Emil 2012-01-11 21:23:01
发布崩溃日志,无法从您的代码中知道。 [编辑评论时,并没有注意到你开始时对'-1'的引用。在代码中会有更清晰的评论。 – XJones 2012-01-11 21:47:49