I am using NSXmlParser to extract a string from an XML file. The xml elements look like the following: <temp_f data="63"/>
I can successfully log the data from the xml tags but when I try to append a string to that data I receive an error saying: Attempt to mutate immutable object with appendString: The tempF is actually a mutable object, it’s declared as an NSMutableString *tempF; in the header file. I have successfully appended strings to NSMutableSrings before but for some reason it is not working in this case. What am I doing wrong, please help?
My code is:
if ([elementName isEqual:@"temp_f"]) {
tempF = [[NSMutableString alloc] init];
tempF = [attributeDict valueForKey:@"data"];
[tempF appendString:@"°F"];
NSLog(@"tempF: %@", tempF);
}
Everything works fine without the appendString: method.
Well, with
you create a new mutable string and assign a pointer to the new object to the variable
tempF, but withdirectly below, you replace the pointer to the new mutable with a pointer to the string allocated by the XML parser to represent the attribute value — which is immutable as it seems. (Note, that you also introduce a memory leak). Try instead: