2011-08-18 56 views
0

什麼是通過循環獲取所有XML項目並將它們分配給Cell.text作爲數組的最佳方式?iPhone TBXML - 通過響應循環

-(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; 

} 

感謝

湯姆

回答

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); 
} 

然後存儲職稱類變量緩衝區(說cellTitles)和tableView:cellForRowAtIndexPath:

Cell.textLabel.text = [cellTitles objectAtIndex:indexPath.row];