views:

511

answers:

2

Hey! i'm using the NSXMLParser to fetch a String from xml. I'v created a class to store the data with synchronized variables. To get the text between the elementName i use the foundCharacter function. And to store the Strings i use a MutableString *. When i find the String and print everything is correct but when i'm done the two different Strings become the same (the last parsed String) in some mysterious way. I have even tried to save the Strings to an array to be sure they are not replaced somehow but even though the Strings become the same??? How can this happen?

PLEASE EXPLAIN SOMEONE!

[xml]

<'name'>USA<'/name'>
<'city'>NEW YORK<'/city'>

[/xml]

[objec*]

  • (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

    //PARSE CITY AND COUNRYNAME if([elementName isEqualToString:@"name"] || [elementName isEqualToString:@"countryName"]){ PARSE_CHARACTER = TRUE; [currentParsedCharacterData setString:@""]; }

}

(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

 if([elementName isEqualToString:@"name"]){
     dataObject.name = currentParseBatch;
     NSLog(@"NAME: %@", dataObject.name);     //OUTPUT: NAME: USA
 }
 if([elementName isEqualToString:@"city"]){
     dataObject.city = currentParseBatch;
     NSLog(@"CITY: %@", dataObject.city);     //OUTPUT: CITY: NEW YORK
 }

 PARSE_CHARACTER = FALSE;

}

(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

 if([elementName isEqualToString:@"name"] || [elementName isEqualToString:@"city"]){
PARSE_CHARACTER = TRUE;
[currentParseBatch setString:@""];
  }

 if(DONE){
   [parser abortParsing];
   NSLog(@"NAME: %@", dataObject.name);  //OUTPUT: NAME: NEW YORK 
   NSLog(@"CITY: %@", dataObject.city);  //OUTPUT: CITY: NEW YORK 
 }

}

(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

if (PARSE_CHARACTER) {
    [currentParseBatch appendString:string];
}

}

[/objec*]

A: 

EDIT: Manged to store the different Strings with two unique Strings except of using the same and append and reset between each load.

N I J E
A: 

The reason you got the output where name and city were the same was that you set the dataObject member pointer to currentParseBatch, so at the end of parsing all the pointers in your data object are equal to the same thing, the currentParseBatch, which is pointing at the last thing the parse found. Instead when you find the end of an element you need to make a new copy of whatever is pointed to by currentParseBatch and have the dataObject member reference that copy.

Nathan Hughes