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

时间:2012-01-04 21:04:42

标签: xcode uitableview removeall

我有一个rss解析器作为我的应用程序代码的一部分,它工作正常并加载rss xml文件并填充tableview正常。

问题在于刷新/重新加载按钮,它会重新加载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崩溃应用程序。

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

2 个答案:

答案 0 :(得分:1)

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

由于数组的“自动释放”元素,所以在清除之后,它们无效。

删除autorelease并在最终的dealloc中释放这些对象。

答案 1 :(得分:0)

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

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

[activityIndicator release];
[activityIndicator startAnimating];

您可以在启动动画时释放activityIdicator。

尝试在功能结束时发布。

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