我正在解析一个相当大的 XML 文件,并将每个项目放入表格 View 上的单元格中。解析 xml 后,它将所有项目添加到 NSMutableArray 中,然后根据数组的计数添加行数。如何设置才能仅将最近 20 个项目添加到数组中,这样加载时间就不会那么长?解析完成后我的代码是:
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil) {
NSLog(@"Failed to parse %@", request.url);
} else {
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries) {
int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
RSSEntry *entry1 = (RSSEntry *) a;
RSSEntry *entry2 = (RSSEntry *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:UITableViewRowAnimationRight];
}
}];
}
}];
}
最佳答案
首先,一次添加所有新行不会有帮助吗?只需将它们全部添加到 _allEntries 数组中,然后重新加载数据,而不是将每一行单独添加到 TableView 中?这可能真的会减慢速度,尤其是当你将其制作成动画时。
至于对最近 20 个条目进行排序,您将需要一种对条目进行排序的方法,排序后只需计算您添加的条目,并在达到 20 时从 for 循环中中断。例如:
int newCounter = 0;
for (RSSEntry *entry in entries) {
newCounter++;
int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
RSSEntry *entry1 = (RSSEntry *) a;
RSSEntry *entry2 = (RSSEntry *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
[_allEntries insertObject:entry atIndex:insertIdx];
//new code
if(newCounter >19)
break;
}
[self.tableview reloadData];
我确信还有其他方法可以做到这一点,但据我所知这应该可以完成这项工作。您也可以在 tableViewController 中处理它。如果数组较长,您可以在 numberOfRows 函数中将行数限制为 20。然后你仍然拥有数组中的所有条目,但只显示 20 个,在上面的示例中,你只在数组中最多存储 20 个条目并显示全部。
关于ios - 仅将 XML 中的 20 个最近项目添加到 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17376614/