2012-05-28 41 views
0

我使用BenPeves的HTMLParser。它工作的很好,但唯一的问题是我不能把输出放在UITableView中。任何人都可以告诉我这段代码有什么问题? .................................................. .................................解析结果在UITableView

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // Do any additional setup after loading the view, typically from a nib. 

    NSError *error = nil; 
    NSURL *url=[[NSURL alloc] initWithString:@"http://website.com/"]; 
    NSString *strin=[[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; 

    HTMLParser *parser = [[HTMLParser alloc] initWithString:strin error:&error]; 

    if (error) { 
     NSLog(@"Error: %@", error); 
     return; 
    } 

    HTMLNode *bodyNode = [parser body]; 
    NSArray *divNodes = [bodyNode findChildTags:@"div"]; 

    for (HTMLNode *inputNode in divNodes) { 
     if ([[inputNode getAttributeNamed:@"class"] isEqualToString:@"views-field-title"]) { 
      NSLog(@"%@", [inputNode allContents]); 

      listData = [[NSArray alloc] initWithObjects:[inputNode allContents], nil]; 
     } 
    }  
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [self.listData count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier]; 

    if (cell == nil) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier]; 
    } 

    NSUInteger row = [indexPath row]; 
    cell.textLabel.text = [listData objectAtIndex:row]; 

    return cell; 
} 

@end 
+0

你可以作为您要发生的事情更清楚一点?你想如何在表格中呈现HTML数据? – 2012-05-29 13:13:37

+0

我想要在UITableView中有一个事件列表,但tableview只显示数组中的最后一个。我把[inputNode allContents]当作一个数组并且试图把它放在“cell.textLabel.text = [listData objectAtIndex:row]”中。在控制台中,它向我显示事件列表,但我只看到单元格中的最后一个事件。我可能会错过一些东西。不知道是什么... – Benjamen

回答

0

您每次发现时都会重新初始化数组一个新元素。我认为你需要移动

listData = [[NSArray alloc] initWithObjects:[inputNode allContents], nil];

外面的循环,并更改为

listData = [[NSMutableArray alloc] init];

listData应该是一个NSMutableArray这样你就可以添加数据。你也需要在你的变量定义中改变它。

那么你的循环中,使用[listData addObject:[inputNode allContents]];

+0

它的工作!非常感谢。 – Benjamen

+0

@Benjamen优秀。听到那个消息很开心! :) –