Tushar Chutani
Tushar Chutani

Reputation: 1570

How to append a string nsxml parser iphone sdk?

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];

}

Upvotes: 1

Views: 528

Answers (1)

zneak
zneak

Reputation: 138161

Casting NSString pointers into NSMutableString pointers doesn't make the underlying objects mutable. You might fool the compiler into thinking it works, but you can't trick the runtime. NSStrings and NSMutableStrings 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 an NSMutableString into a NSString, 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 NSMutableString objects. The easiest way to get a mutable representation of an immutable string is to use the mutableCopy instance method. (Don't forget to release the objects as you go.)

[data appendFormat:string]; 
[data autorelease];
data = [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] mutableCopy];

Upvotes: 3

Related Questions