views:

219

answers:

1

I am having a heck of a time with this -- I am trying to parse an XML file and set the text in a NSMutableString variable in order to later fill in a label's text as you can see below.

In my .h I have the following (simplified);

NSMutableString *contentsOfCurrentXMLProperty;
@property (nonatomic,retain) NSMutableString *contentsOfCurrentXMLProperty;

In my .m:

-(void) parseData {
  NSXMLParser *parser = [[NSXMLParser alloc] initWithData:myData];
  [parser setDelegate:self];
  [parser parse];
  [parser release];
}



 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    if ([elementName isEqualToString:@"Title"]) {
 NSLog(@"FOUND TITLE!");
 contentsOfCurrentXMLProperty = [NSMutableString setString:@""];
    }
 }

 -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if ([elementName isEqualToString:@"TITLE"]) {
       myLabel.text = [contentsOfCurrentXMLProperty stringByReplacingOccurrencesOfString:@"[br]" withString:@"\n"];
    }
 }

 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
[self.contentsOfCurrentXMLProperty appendString:string];
 }

When I run my app, the data is downloaded and parsed correctly. I run into issues when my observer fires off the event again. The parseData method is called and I get an error that I have traced to the line that reads: "contentsOfCurrentXMLProperty = [NSMutableString setString:@""]; "

What is the proper way to create or init a NSMutableString variable for me to use over and over? When/Where is the best place to release it? How do I essentially clear the variable so that when the observer fires off the parseData method it will again be able to set "contentsOfCurrentXMLProperty"?

+1  A: 

-setString: is an instance method, not a class method. If you already have a valid NSMutableString object assigned to contentsOfCurrentXMLProperty and simply want to clear it, then:

contentsOfCurrentXMLProperty = [NSMutableString setString:@""];

should be

[contentsOfCurrentXMLProperty setString:@""];

On the other hand, if you want to assign a new object to contentsOfCurrentXMLProperty, here's one valid way to do it:

self.contentsOfCurrentXMLProperty = [NSMutableString stringWithCapacity:0];
Mike McMaster
That did the trick. Do I just do [contentsOfCurrentXMLProperty release] in my dealloc?
SonnyBurnette
Yep, that's correct.
Mike McMaster