I'm currently in the process of teaching myself Objective-C; so far no bumps in the road, with the exception of the following. Here is some code:
int main (int argc, char *argv[])
{
Fraction *aFraction = [[Fraction alloc] init]
Fraction *sum = [[Fraction allow] init], *sum2;
int i;
...
for (i=1; i<=n; ++i) {
[aFraction setTo: 1 over: 16]
sum2 = [sum add: aFraction];
[sum free];
sum = sum2;
}
.....
[aFraction free];
[sum free];
return 0;
}
Here are parts of the interface:
-(void) setTo: (int) n over: (int) d; // sets numerator and denominator
-(Fraction *) add: (Fraction *) f; // adds one fraction to another
So, what I am not entirely clear about is the role of "[sum free]". Here is what I see going on. At the start, we create objects aFraction and sum. The add: method creates an object of type Fraction, and returns that object. The object that is returned is assigned to sum2 (by "sum2 = [sum add: aFraction]").
Here is where I get confused. "[sum free]" releases sum; so that object no longer exists. Now, I think "sum = sum2" makes sum point to the same object as sum2. Then on the next run through the loop, sum2 gets the new object, the object to which sum points is released, and so on. If we did not do this, we could end up with a large number of unreleased objects ... correct?
Also, if we had the following,
sum2 = [sum add: aFraction];
sum = sum2;
[sum2 free];
would this mean that sum2 would be released, but that sum would simultaneously be released (since sum and sum2 refer to the same object)?
Thanks for the help.