RE: Another memory question
RE: Another memory question
- Subject: RE: Another memory question
- From: "Jonathan E. Jackel" <email@hidden>
- Date: Tue, 26 Aug 2003 16:23:20 -0400
>
In the code fragment below I reassign a new value to an
>
NSString. (I have seen others do that as well.)
>
>
- (void)awakeFromNib {
>
>
NSString *demoFile;
>
>
demoFile = [NSString stringWithString: @"~/Application User
>
Data/dsf.plist"];
>
demoFile = [demoFile stringByExpandingTildeInPath];
>
// more code
>
}
>
>
If I have understood it correctly, the second assignment creates
>
a new memory block for the string, and the first string is still
>
in memory, but can no longer be accessed.
>
>
My questions are:
>
>
1) Will the auto release process release the first block or
>
will there be a memory leak?
Yes, the first string that demofile is set to point at is autoreleased.
More generally, it is OK to assign a new object to a variable, so long as
the old object that the variable pointed to is released or autoreleased.
(This is what goes on in your typically "setter" accessor.)
>
>
2) Is the above example good practice, or would the following
>
have been better:
>
>
>
- (void)awakeFromNib {
>
>
NSString *demoFile;
>
>
NSString *temp = [[NSString alloc] init];
>
temp = [NSString stringWithString: @"~/Application User
>
Data/dsf.plist"];
>
demoFile = [temp stringByExpandingTildeInPath];
>
[demoFile release];
No No No No! You are leaking! First you are allocating an empty string
which you own, and then you are abandoning it by reassigning temp to a new,
autoreleased string. The string you own (temp = [[NSString alloc] init])
never gets deallocated. The thing you release is the thing temp points at
when you send it the release message. In other words, an autoreleased
string. Then your app goes kablooey. Sad, really.
I would use alloc/init in this situation only if I found that the
autoreleased version was too slow or I wanted more control over when the
object gets released. Those conditions are pretty rare. It's completely OK
to do it the first way. I find I do the same thing alot when doing
arithmetic on NSDecimalNumbers, e.g.,
NSDecimalNumber * result = [NSDecimalNumber decimalNumberWithString:@"5"];
result = [result decimalNumberByAdding:[NSDecimalNumber one]];
That said, the preferred way of doing this (at least where it doesn't make
your code unreadable) is to nest your terms:
NSString *demofile = [[NSString stringWithString: @"~/Application User
>
Data/dsf.plist"] stringByExpandingTildeInPath];
NSDecimalNumber * result = [[NSDecimalNumber decimalNumberWithString:@"5"]
decimalNumberByAdding:[NSDecimalNumber one]];
Jonathan
_______________________________________________
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.