Re: Some confusion on memory management
Re: Some confusion on memory management
- Subject: Re: Some confusion on memory management
- From: Jeff Gilbert <email@hidden>
- Date: Fri, 20 Jan 2006 09:32:29 -0600
Hi Mike,
On Friday, January 20, 2006, at 09:09AM, Mike Abdullah <email@hidden> wrote:
>I am still getting to grips with Cocoa, and would like to ask a
>question on memory management that will hopefully clear things up for
>me.
It certainly can take a while for all the memory stuff to click.
>I have my subclass of NSDocument, and my document window contains a
>single text view.
>
>The idea, is that every time, the text in the text view is changed by
>the user, my NSDocument will change its internal value accordingly.
>I have the delegate system for the text view set up fine, so that
>when the text does change, I carry out the command:
>
>[self setMyString: newString];
>
>So, in my class there are 2 methods: setMyString and myString. The
>thing I don't fully understand is how to properly get the internal
>value of myString to be remembered throughout the life of the
>NSDocument. In my header file I have placed:
>
>NSString *myString;
>
>And in the two methods I have this:
>
>- (void)setMyString:(NSString *)newString
>{
> myString = newString;
>}
>
>-(NSString *)myString
>{
> return myString;
>}
>
>However, I am sure this is not entirely correct, since it seems that
>after a while, the NSDocument "forgets" the value of myString, so I
>am sure that I have the memory management wrong! Also, should I
>really be using NSString? Would I be better off with NSMutableString?
The way you do it above you simply copy the pointer to newString; you do not copy the value of newString. The problem with this is that you do not know the lifetime of newString. It is certainly possible that newString will de deallocated in the near future. Since myString simply points to the newString object, when newString is deallocated the string that myString points to simply vanishes. This is why your document "forgets" the value of myString.
Instead, you want to make your own private copy of the value of newString so that you can control the lifetime of the string. So, you would do something like this:
- (void)setMyString:(NSString *)newString
{
[myString release]; // forget about the old value of myString
myString = [newString copy];
}
- (void)dealloc
{
// be sure to release myString when the document is deallocated
[self setMyString:NULL];
}
You only need to use NSMutableString if you plan on changing the value of myString after it is copied. If you do not otherwise manipulate myString then NSString is fine.
Good luck,
Jeff
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden