Hi,
I'm going through Kochran's "Programming in Objective-C 2.0" and I have a question about releasing objects allocated from an object's instance method as shown in Program 7.6 on page 153-154.
I'm trying to figure out how sum2 is released where only sum is explicitly released in the for loop and at the end of the main function.
I notice that sum is released just before the sum = sum2 statement and I was wondering exactly what the = sign does. I thought that it set the instance variables in the sum object equal to those in the sum2 object.
Clearly I'm wrong but I would like some help understanding exactly what occurs when I write sum = sum2.
Here is the Main Code
I'm going through Kochran's "Programming in Objective-C 2.0" and I have a question about releasing objects allocated from an object's instance method as shown in Program 7.6 on page 153-154.
I'm trying to figure out how sum2 is released where only sum is explicitly released in the for loop and at the end of the main function.
I notice that sum is released just before the sum = sum2 statement and I was wondering exactly what the = sign does. I thought that it set the instance variables in the sum object equal to those in the sum2 object.
Clearly I'm wrong but I would like some help understanding exactly what occurs when I write sum = sum2.
Here is the Main Code
Code:
#import "Fraction.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *aFraction = [[Fraction alloc] init];
Fraction *sum = [[Fraction alloc] init];
Fraction *sum2; // sum2 is allocated by "add" method
int i, n, pow2;
[sum setNumerator: 0 setDenominator: 1]; // initilize sum to 0
NSLog(@"Enter your falue for n");
scanf ("%i", &n);
pow2 = 2;
for (i = 1; i <= n; ++i) {
[aFraction setNumerator: 1 setDenominator: pow2];
sum2 = [sum add: aFraction];
[sum release]; // release previous sum
sum = sum2;
pow2 *= 2;
}
NSLog(@"After %i iterations, the sum is %g", n, [sum convertToNumber]);
[aFraction release];
[sum release];
//[sum2 release];
[pool drain];
return 0;
}