I’m getting EXC_BAD_ACCESS while parsing XML file in my Xcode4 iPhone app
Although I read many similar errors questions here but couldn’t figure out how to fix my code!
It crashed at the [parser parse]
Then I enabled NSZombieEnabled and got the following error:
*** -[CFString appendString:]: message sent to deallocated instance 0x588c3a0
The following is my code related to the parsing section:
-(void)openXML {
NSURL *url = [NSURL URLWithString:@"http://localhost/news.xml"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:req delegate:self];
[con release];
}
-(void)parseXMLData:(NSData *)xmlData{
parser = [[NSXMLParser alloc] initWithData:xmlData];
parser.delegate = self;
[parser parse];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
xmlDocument = [[NSMutableData alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[xmlDocument appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self parseXMLData:xmlDocument];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser{
[offersData removeAllObjects];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
completeString = [[NSMutableString alloc] init];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
[offersData addObject:completeString];
[completeString release];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
[completeString appendString:string];
}
- (void)parserDidEndDocument:(NSXMLParser *)parser{
[offersTableView reloadData];
}
The message means the code is trying to call a method on a string object (meaning it’s not nil) but the object has been deallocated (released).
In
didEndElement, you are releasingcompleteStringbut not setting it tonil. This makes the error you’re getting possible.What’s probably happening is after
didEndElement,foundCharactersis getting called before adidStartElement(maybe there’s some whitespace like a new line between tags) so thecompleteStringis still deallocated resulting in a crash.After doing
[completeString release];also set it tonilso any method calls that might be done on it before it gets re-allocated will not crash.It would also then be a good idea to only do the
addObjectif completeString is notnil(which could happen depending on how the xml tags are nested).So try changing
didEndElementto: