NSXMLParser how to pass the NSMutableDictionary to a NSMutableArray

社会主义新天地 提交于 2019-12-13 05:38:33

问题


I would like to pass the nsdictionary I am creating into an nsmutablearray but I'm not sure when or how to do it in the nsxmlparser delegates.

this is what I have done so far

#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:


In -parser:didEndElement:namespaceURI:qualifiedName:, listen for the end of the item element, then add valueDictionary to a mutable array instance on your class.

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


来源:https://stackoverflow.com/questions/8596824/nsxmlparser-how-to-pass-the-nsmutabledictionary-to-a-nsmutablearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!