NSXMLParser如何将NSMutableDictionary传递给NSMutableArray

时间:2011-12-21 21:47:08

标签: iphone ios nsmutablearray nsxmlparser nsmutabledictionary

我想将我正在创建的nsdictionary传递给nsmutablearray,但我不确定在nsxmlparser委托中何时或如何执行此操作。

这是我到目前为止所做的事情

#pragma mark - Parsing lifecycle

- (void)startTheParsingProcess:(NSData *)parserData
{    
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:parserData]; //parserData passed to NSXMLParser delegate which starts the parsing process 

    [parser setDelegate:self];
    [parser parse]; // starts the event-driven parsing operation.
}


- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict 
{
    if ([elementName isEqualToString:@"item"]) {
        valueDictionary = [[NSMutableDictionary alloc] init];
    }    
}

-(void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
    NSMutableString *dicString = [[NSMutableString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
    currentElement = dicString;
}



- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
{
    if ([elementName isEqualToString:@"title"]) {
        titleString = currentElement;
        [self.valueDictionary setObject:titleString forKey:@"title"];

        NSLog(@"%@", [valueDictionary objectForKey:@"title"]);
        NSLog(@" ");
        currentElement = nil;
    }
    if ([elementName isEqualToString:@"description"]) 
    {
        descriptionString = currentElement;
        [self.valueDictionary setObject:descriptionString forKey:@"description"];

        NSLog(@"%@", [valueDictionary objectForKey:@"description"]);
        NSLog(@" ");
        currentElement = nil;
    }

1 个答案:

答案 0 :(得分:2)

-parser:didEndElement:namespaceURI:qualifiedName:中,侦听item元素的结尾,然后将valueDictionary添加到您班级的可变数组实例中。

if ([elementName isEqualToString:@"item"])
{
    [self.mutableArrayOfDictionaries addObject:self.valueDictionary];
}

if ([elementName isEqualToString:@"title"]) {
    titleString = currentElement;
    [self.valueDictionary setObject:titleString forKey:@"title"];

    NSLog(@"%@", [valueDictionary objectForKey:@"title"]);
    NSLog(@" ");
    currentElement = nil;
}

if ([elementName isEqualToString:@"description"]) 
{
    descriptionString = currentElement;
    [self.valueDictionary setObject:descriptionString forKey:@"description"];

    NSLog(@"%@", [valueDictionary objectForKey:@"description"]);
    NSLog(@" ");
    currentElement = nil;
}