循环使用它来获取所有XML项目并将它们作为数组分配给Cell.text的最佳方法是什么?
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (Cell == nil) {
Cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
TBXML * XML = [[TBXML tbxmlWithURL:[NSURL URLWithString:@"http://www.tomstest.info/ios/results.xml"]] retain];
TBXMLElement *rootXML = XML.rootXMLElement;
TBXMLElement *results = [TBXML childElementNamed:@"location" parentElement:rootXML];
TBXMLElement *WOEID = [TBXML childElementNamed:@"CompanyName" parentElement:results];
NSString *woeid = [TBXML textForElement:WOEID];
Cell.text = woeid;
return Cell;
}
由于
汤姆
答案 0 :(得分:1)
首先,您真的不应该在tableView:cellForRowAtIndexPath:
下载文件的内容。每个单元格调用一次该方法:您最终会多次下载xml文件。
TBXML
不支持XPath查询,因此您必须遍历结果。
像
NSMutableArray *cellTitlesBuffer = [NSMutableArray array];
TBXMLElement *locationNode = [TBXML childElementNamed:@"location" parentElement:rootXML];
if (locationNode) {
NSString *cellTitle = nil;
do {
TBXMLElement *woeidNode = [TBXML childElementNamed:@"CompanyName" parentElement:locationNode];
[cellTitlesBuffer addObject:[TBXML textForElement:woeidNode]];
} while (locationNode = locationNode->nextSibling);
}
然后将titles缓冲区存储在类变量(比如cellTitles)和tableView:cellForRowAtIndexPath:
Cell.textLabel.text = [cellTitles objectAtIndex:indexPath.row];