Re: stringByReplacingCharactersInRange leading to bus error
Re: stringByReplacingCharactersInRange leading to bus error
- Subject: Re: stringByReplacingCharactersInRange leading to bus error
- From: vincent habchi <email@hidden>
- Date: Wed, 18 Aug 2010 06:43:25 +0200
Le 17 août 2010 à 23:03, James Miller a écrit :
> // NSString *level = [[NSString alloc]
> // initWithContentsOfFile:path
> // encoding:NSUTF8StringEncoding
> // error:&error];
>
>
> During the timer call, the level NSString is modified by the following line of code:
>
> level=[level stringByReplacingCharactersInRange:NSMakeRange(5,1) withString:@" "];
>
> This operation appears to succeed as I print it via NSLog and it looks fine and the length checks out, but the next time through the NSTimer I get a bus error and the application dies.
Since NSString is an immutable type, the first certain thing is that you will leak your first allocation, since as soon as you call your second line, you lose the reference to the original string ([level stringByReplacing…] does not modify the string in place, it rather returns you a pointer to a newly created string).
Next, you should retain the result of [level stringBy…]: this method returns autoreleased strings, that may or may not exist anymore when you call your method again after the timer fires.
You'd have to write this:
NSString * level = [[NSString alloc] …]
…
[level autorelease];
level = [[level stringBy…] retain];
Cheers
Vincent_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden