Amazon.com Widgets Object Memory Release Question
Welcome, Guest. Please login or register.
Did you miss your activation email?
May 19, 2013, 08:29:10 PM
Home Help Search chat Login Register   
News: Read this please.The Great Kangaroo Escape Looking for reviews of the 4th ed on Amazon!   Twitter:  @skochan
                     

+  Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
|-+  Old Stuff
| |-+  Help!!!
| | |-+  Object Memory Release Question
Pages: [1]   Go Down
Print
Author Topic: Object Memory Release Question  (Read 402 times)
tmekeel
Newbie
*
Posts: 18


WWW




« on: November 16, 2009, 09:10:39 PM »

What is the difference between the Fraction *answer object and the origin object in these two code examples?
What I'm trying to figure out is where did I release (or was supposed to) release the *answer pointer?  Does releasing the myFract object in main take care of the pointer in the add method? I feel like I'm missing a fundamental point about memory allocations  Huh
The origin object is created in the setOrigin method, so we have to deallocate it there as well, but why not [Fraction *answer]?

Code: (Objective-C)
-(Fraction *) add: (Fraction *) f
{
//Tp add two fractions:
// a/b +c/d = ((a * d)+(b * c)) / (b * d)
Fraction *answer = [[Fraction alloc] init];

answer.numerator = (numerator * f.denominator) + (denominator * f.numerator);
answer.denominator = denominator * f.denominator;

[answer reduce];
return answer;
}

Code: (Objective-C)
-(void) setOrigin: (XYPoint *) pt
{
if (origin)
[origin release];

origin = [[XYPoint alloc] init];

[origin setX: pt.x andY: pt.y];
}
Logged
skochan
Administrator
Hero Member
*****
Posts: 3103







« Reply #1 on: November 17, 2009, 04:23:35 AM »

In the case of the Rectangle class, origin is an instance variable, so you have  a handle on the object and can therefore release it in the dealloc method.   In the case of the Fraction's add: method, the allocated fraction is not stored in an instance variable and is returned as the result of the addition.  Further, you may end up allocating many fractions if you add a lot of fractions.  Because of these reasons, a different approach is needed:  either each allocated fraction has to be released by the caller of the method (e.g., inside main) or else each fraction needs to be added to the autorelease pool by sending it an autorelease message (as discussed later in the text), so it will be released when the autorelease pool gets drained.

Cheers,

Steve Kochan
« Last Edit: November 17, 2009, 07:38:00 AM by skochan » Logged
tmekeel
Newbie
*
Posts: 18


WWW




« Reply #2 on: November 17, 2009, 06:45:41 AM »

Thanks Steve  Grin

 
Logged
Pages: [1]   Go Up
Print
Jump to:  



Login with username, password and session length

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents (c) 2009 classroomM.com. All rights reserved.