Re: converting C-strings to NSString
Re: converting C-strings to NSString
- Subject: Re: converting C-strings to NSString
- From: Drew McCormack <email@hidden>
- Date: Tue, 23 Oct 2001 09:22:17 +0200
On Tuesday, October 23, 2001, at 04:26 , email@hidden wrote:
Hello.
I have been working on this bug for a while, and I can't seem to figure
out what the problem is. I am first converting a C-string into NSString
using the following syntax:
NSString * scratch;
NSString * secondbuffer;
char buffer[2];
...
[secondbuffer init];
(in a loop)
[scratch initWithCString: buffer];
secondbuffer = [secondbuffer stringByAppendingString: scratch];
In case you haven't realized, "stringByAppendingString:" returns an
autoreleased string. Unless you retain it, it will be released at the
end of the current event loop. If you need to use it elsewhere, you
should retain it.
But be careful, because in your loop you will need to autorelease the
last string that secondbuffer pointed too.
Eg
[[secondbuffer alloc] init];
(in a loop)
[[scratch alloc] initWithCString:buffer]];
[secondbuffer autorelease]; // free up last string before
assigning to new one
secondbuffer = [secondbuffer stringByAppendingString:scratch];
[secondbuffer retain];
[scratch release];
and later
[secondbuffer release];
Drew McCormack