Re: Memory Mania Revisted
Re: Memory Mania Revisted
- Subject: Re: Memory Mania Revisted
- From: John Hörnkvist <email@hidden>
- Date: Fri, 8 Feb 2002 07:33:24 +0100
On Friday, February 8, 2002, at 06:48 AM, email@hidden wrote:
Ok, I did a little reading up on memory allocation, release/retain
stuff, but I'm still a little bit confused about the specifics...
Here's some hypothetical code:
NSDecimalNumber *myDN = (NSDecimalNumber *)[NSDecimalNumber
numberWithFloat:2.5];
NSDecimalNumber *myOtherDN = (NSDecimalNumber *)[NSDecimalNumber
numberWithFloat:4.5];
// Suppose I want to take these two NSDecimalNumbers and add one to the
other like this:
myDN = [myDN decimalNumberByAdding:myOtherDN];
...
OK... I _think_ there's a leak here, because - (NSDecimalNumber
*)decimalNumberByAdding:(NSDecimalNumber *)dn creates a new instance of
NSDecimalNumber, right? then the original myDN memory is lost because
I've reassigned the pointer without deallocating this. My question is,
what is the best strategy for eliminating this leak? I do this step a
lot in my code, and I don't want to have to write 4 lines whenever I do
it...
There is no leak unless you explicitly call "alloc*" "copy*" or "retain".
A method like numberWithFloat: looks something like this:
+ (NSNumber*)numberWithFloat:(float)someFloat
{
return [[[self alloc] initWithFloat:someFloat] autorelease];
}
What can happen when you're dealing with autoreleased objects is
"dangling references" --- the opposite of a leak --- you forget to
retain an object and use it after the autorelease pool has been "popped".
The advantages of using autoreleased objects are:
1) Fewer leaks.
2) Simpler code.
The disadvantages of using autoreleased objects are:
1) Some extra time is needed to put it in the pool
2) Objects live longer than required, increasing memory use
3) Dangling references are difficult to find; when there is a problem
the program often crashes while deallocating the pool.
Experience has taught me to avoid autorelease when it is easy to do so.
Regards,
John Hornkvist
--
ToastedMarshmallow, the perfect Cocoa companion
http://www.toastedmarshmallow.com
_______________________________________________
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.