Xcode表视图重载不断向表中添加数据



我有一个rss解析器作为应用程序代码的一部分,它运行良好,加载rss xml文件并填充表视图也很好。

问题在于刷新/重新加载按钮,它确实会重新加载rss数据,但它会将新数据添加到表中,并且表的大小会不断增加。

行为应该做的是清除旧的表数据,并用新数据重建表,这样表总是只显示一组数据,而不会在每次按下重载/刷新时不断增长。

表格构建代码如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
cell.textLabel.text = [[stories objectAtIndex: storyIndex] objectForKey: @"date"];
cell.detailTextLabel.text = [[stories objectAtIndex: storyIndex] objectForKey: @"title"];
[cell.textLabel setLineBreakMode:UILineBreakModeWordWrap];
[cell.textLabel setNumberOfLines:0];
[cell.textLabel sizeToFit];
[cell.detailTextLabel setLineBreakMode:UILineBreakModeWordWrap];
[cell.detailTextLabel setNumberOfLines:0];
[cell.detailTextLabel sizeToFit];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}

重新加载/刷新按钮代码为:

- (void)reloadRss {
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
[[self navigationItem] setLeftBarButtonItem:barButton];
[barButton release];
[activityIndicator release];
[activityIndicator startAnimating];
[self performSelector:@selector(parseXMLFileAtURL) withObject:nil afterDelay:0];
[newsTable reloadData];
}

我试图通过添加以下行来解决此问题:

if (stories) { [stories removeAllObjects]; }

重新加载部分,我认为这应该有效,并且确实清除了表,但应用程序随后用EXC_BAD_ACCESS崩溃了应用程序。

非常感谢您的任何想法或建议!

实际上,现在已经解决了这个问题!

是由于数组中的"自动释放"元素,所以在清除此元素后,它们是无效的。

删除autorelease并在最终解除锁定时释放这些对象是有效的。

代码EXC_BAD_ACCESS的意思是,您希望连接到一个不再存在的变量。

在您的代码示例中,我可以看到,问题在于以下两行代码:

[activityIndicator release];
[activityIndicator startAnimating];

在开始动画制作之前,请先释放activityIdicator。

尝试在函数结束时释放。

[activityIndicator startAnimating];
[self performSelector:@selector(parseXMLFileAtURL) withObject:nil afterDelay:0];
[newsTable reloadData];
[activityIndicator release];

最新更新