views:

41

answers:

2

I am manipulating a large string by removing chunks of characters, and assigning the new string back to the original string.

articleString = [articleString stringByReplacingCharactersInRange:startRange withString:@""];

articleString is an instance variable of type NSMutableString

This seems to work fine the first time I go through this code. But when I return from the second time through, and use the variable articleString, I get an EXC_BAD_ACCESS exception.

These are long strings - up to 100K bytes.

Any ideas why I am getting the exception?

+1  A: 

Please post the whole code block so we can figure out what's happening :)

My guess is that this is happening because of an autorelease inside your method block and then assigning it back to the original variable. If you are creating a new string either with the static stringWithFormat, or an autorelease that string, no matter what you do with it will have it's reference counter decremented when you exit the code block. This means that if you are assigning it back to the original string, your original string will now be released the second time in, causing your EXE_BAD_ACCESS.

The solution in that case would be to either mutate the existing NSMutableString, or retain the string and release it later when it is safe. For example, using replaceCharactersInRange:withString: instead may fix the problem.

slf
+2  A: 
Eld