Re: [newbie] NSString code so it won't leak, again
Re: [newbie] NSString code so it won't leak, again
- Subject: Re: [newbie] NSString code so it won't leak, again
- From: "Clark S. Cox III" <email@hidden>
- Date: Tue, 10 Sep 2002 11:10:39 -0400
On 09/10/2002 10:00, "Dean Davis" <email@hidden> wrote:
>
Sorry, the first posting got screwed by Yahoo.
>
>
In languages I'm used to you could write code like...
>
>
myString = "SOME BIG LONG ... STRING"
>
string1 = left(myString,40)
>
myString = mid(myString,41)
>
>
Thereby isolating the first 40 characters to string1
>
and the balance going back into myString
>
>
In Cocoa I was using...
>
NSString *string1,*myString
>
>
string1 = [myString stringToIndex:41];
>
myString = [myString stringFromIndex:41];
>
>
This works but leaks.
I'd be inclined to say that no, it doesn't leak. Take this code for
example:
NSString *string1;
/*This string is created at compile time, and never goes away.
This is not a leak, but is how it is supposed to work*/
NSString *myString = @"SOME BIG LONG ... STRING";
/*These two strings are created at runtime, and are created "autoreleased"
This means that these strings will stay around until the current
NSAutoreleasePool is cleared out (which usually means the next time through
the event loop)
*/
string1 = [myString stringToIndex:41];
myString = [myString stringFromIndex:41];
>
So what's better?
>
All I've come up with is
>
string1 = [myString stringToIndex:41];
>
myString2 = [myString stringFromIndex:41];
This line has no effect, releasing a compile-time string does nothing:
>
[myString release];
>
myString = [myString2 stringFromString:myString2];
These are very different. "stringFromString:" returns a new, autoreleased
string, while "copy" returns a new, NOT autoreleased string
>
// or? myString = [myString2 copy];
>
[myString2 release];
>
>
Would simply making myString as a NSMutableString make
>
the first code section not leak?
I suggest you read
<
http://developer.apple.com/techpubs/macosx/Cocoa/ObjectiveC/index.html>,
paying special attention to: retain/release and autorelease.
--
http://homepage.mac.com/clarkcox3/
Clark S. Cox III
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.