Hello,
i've now spent nearly an hour looking at those 2 pages (144-145) and program 7.6, and first of all, i don't get the correct output, and second of all, i find it hard to grasp, even after reading this post - http://classroomm.com/objective-c/index.php?topic=56.0
I think i may have gotten close, so how is my understanding here:
Fraction *sum = [[Fraction alloc] init], *sum2;
This creates a Fraction Object in memory. The variable sum has reserved enough space to hold a Fraction object. Due to the assignment operator '=' it points to that particular Fraction in memory created on that line.
sum2 is pretty much an empty variable with enough reserved space to store a Fraction in, but does not hold a reference to any allocated object yet.
for ( i = 1; i <= n; ++i ) {
[aFraction setTo: 1 over: pow2];
sum2 = [sum add: aFraction];
[sum release]; // release previous sum
sum = sum2;
pow2 *= 2;
}Now, this is the hard one i think. aFraction gets set, not much to that.
sum calls the add method. sum is now the sender / receiver of the message, and aFraction the argument passed along for the ride.
In the add method we return a Fraction object that we also initialize in memory, meaning that "result" in the add method, will return it's reference to that object in memory, and assign that reference to sum2. Meaning that now sum2 holds a reference, to the newly created Object in memory, which holds the addition of sum and aFraction.
[sum release]; sum is released, and i am not sure as to why it is? if you release sum, you remove it's reference to the object in memory, but don't you destroy the object as well? then how can you assign the value of sum2 to sum, if you destroy the object?
sum = sum2; Confused about this? But i THINK that now sum is just an empty variable that holds no reference to anything, but still holds enough space to reference a Fraction object. It then gets passed the reference that sum2 holds, which is the addition of the old sum and aFraction.
I'm sorry if this seems messy, but i can't really move forward in the book until i get this straightened out. Here is my main routine, coz i can't get that working properly either.
Help
main.m #import <Foundation/Foundation.h>
#import "Fraction.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *sum = [[Fraction alloc] init], *sum2;
Fraction *aFraction = [[Fraction alloc] init];
int i, n, pow2;
[sum setTo:0 over: 1]; // set 1st fraction to 0
NSLog (@"Enter your value for n:");
scanf("%i", &n);
pow2 = 2;
for ( i = 1; i <= n; ++i ) {
[aFraction setTo: 1 over: pow2];
sum2 = [sum add: aFraction];
[sum release]; // release previous sum
sum = sum2;
pow2 *= 2;
}
NSLog (@"After %i iterations, the sum is %g", n, [sum convertToNum]);
[aFraction release];
[sum release];
[pool drain];
return 0;
}