I am parsing an rss and I want to appenend a string here is some code. My application crashes for and this is what is NSLogged.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with appendFormat:'
I am appending an nsmutablestring
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
// [data appendFormat:(NSMutableString *)string]; this doesn't work either
[data appendFormat:string];
data = (NSMutableString *)[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
why is my app carshing and what can I do to fix it?
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
[data appendFormat:string];
[data autorelease];
data = [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] mutableCopy];
}
Casting
NSStringpointers intoNSMutableStringpointers doesn’t make the underlying objects mutable. You might fool the compiler into thinking it works, but you can’t trick the runtime.NSStrings andNSMutableStrings are different beasts to start with, so you can’t go around, take an immutable string, and pretend it’s mutable. Your app crashes because of this. (The opposite, casting anNSMutableStringinto aNSString, works because you’re restricting the set of possible operations on the object. You can always cast an object down to a more restrictive form, but you can rarely cast them the other way around.)You need to work with actual
NSMutableStringobjects. The easiest way to get a mutable representation of an immutable string is to use themutableCopyinstance method. (Don’t forget to release the objects as you go.)