【问题标题】:Can't store data using NSXML parser in a NSMutableArray无法在 NSMutableArray 中使用 NSXML 解析器存储数据
【发布时间】:2011-07-30 00:45:12
【问题描述】:

我想使用 NSXml 解析器从 web 服务获取数据。我能够接收数据(我可以看到使用 NSLog。但我无法将数据保存在数组中。这是我的代码。

- (void)parser:(NSXMLParser *)parser 
    didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI 
 qualifiedName:(NSString *)qName 
    attributes:(NSDictionary *)attributeDict {
    if([elementName isEqual:@"entry"]) {
        NSLog(@"Found a title entry");
        getXMLFlag = YES;
    }

    if ([elementName isEqual:@"title"] && getXMLFlag) {

        NSLog(@"found title!");
        PTString = [[NSMutableString alloc]init];
    }   
}

- (void)parser:(NSXMLParser *)parser 
 didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI 
 qualifiedName:(NSString *)qName 
{
    namazXmlArray= [[NSMutableArray alloc] initWithObjects:@"tab1",@"1tab1",nil];

    if ([elementName isEqual:@"title"] && getXMLFlag) {
        NSLog(@"ended title: %@",PTString);

        //      namazXmlArray= [[NSMutableArray alloc] initWithObjects:@"tab1",@"1tab1",nil];
        [namazXmlArray addObject:PTString];
        NSLog(@"I can't add this in array: %@",PTString);
        //Release and nil title String so that the next time characters are found and not within a title tag, they are ignored
        [PTString release];
        PTString = nil;
    }
    if ([elementName isEqual:@"entry"]) {
        NSLog(@"ended a namaz entry");
        getXMLFlag = NO;
    }
}

【问题讨论】:

  • PTString 是属性/字段吗?控制台说什么?

标签: iphone objective-c xcode nsxmlparser


【解决方案1】:

您似乎将一个数组添加到另一个数组。我不太清楚为什么,如果没有完整的代码,很难看出你在做什么。这并没有具体回答您的问题,但作为您的 iPhone 编程新手,您可能希望查看我为 XML 解析提供的类。然后,您将能够仅使用几行代码解析文件。您可以通过GitHub here 获取它。

P.S 发帖时将所有代码放在代码括号中。更容易阅读:)

更新 在数组中获得数据后,您需要执行以下操作:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [array count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      ....
         cell.textLabel.text = [[array objectAtIndex:storyIndex] objectForKey:@"title"];

}

【讨论】:

  • 感谢 kmcgrady 的帮助,现在我可以将数据存储在数组中,但我无法在表格视图中显示这些数据(但我可以在表格视图中显示静态数据),你能帮忙吗我在这,但是
  • 我已经更新了我的答案,以展示如何从数组中获取数据并将其显示在表格中。将“标题”替换为“摘要”或“链接”以获取其他数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-15
  • 1970-01-01
  • 1970-01-01
  • 2012-07-14
  • 2012-02-29
  • 1970-01-01
相关资源
最近更新 更多