开发者

EXC_BAD_ACCESS after modifying string

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 a开发者_如何学运维re long strings - up to 100K bytes.

Any ideas why I am getting the exception?


stringByReplacingCharactersInRange:startRange would return a copy of type NSString. (Not NSMutableString)
you want to use:
- (void)replaceCharactersInRange:(NSRange)aRange withString:(NSString *)aString instead.

stringByReplacingCharactersInRange:startRange returns an autoreleased NSString so you would have to call retain on it if articleString is a member variable.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜