I'm trying to understand an example in the Kochan Obj-C 2.0 book. It looks like this. Basically we have a standard add fraction method:
-(Fraction *)add:(Fraction *) f {
Fraction *result = [[Fraction alloc] init];
int resultNum, resultDenom;
resultNum = nermator *f.denominator + denominator*f.numerator;
resultDenom = denominator *f.denominator
// numerator and denominator are instance variables
[result setTo: restultNum over: resultDenom]; // another method that sets the fraction (e.g. 1/4)
[result reduce];
return result}
There are two examples using this that I don't understand, one in a main.m test file they do:
Fraction *aFraction = [[Fraction alloc] init];
Fraction *bFraction = [[Fraction alloc] init];
Fraction *resultFraction;
[aFraction setTo: 1 over: 4];
[bFraction setTo: 1 over: 2];
resultFraction = [aFraction add: bFraction];
I don't understand why you don't need to alloc and init resultFraction before using the add method. (Question #1) Also, by doing this, does resultFraction now have a reference count of 1? Or because it was never alloc'd and init'd, is it's reference count still 0?
Using the same Fraction class and methods, they show an example of how to calculate the summation of 1/2^n
Here is the code:
Fraction *aFraction = [[Fraction alloc] init];
Fraction *sum = [[Fraction alloc] init], *sum2;
int i, n, pow2;
[sum setTo: 0 over:1]; // set 1st fraction to 0
NSLog(@"Enter n:");
scanf("%i", &n);
pow2 = 2;
for (i = 1; i <=n; ++i) {
[aFraction setTo: 1 over: pow2];
sum2 = [sum add: aFraction];
[sum release];
sum = sum2;
pow2 *=2;
}
In this example, sum is alloc'd and init'd, and added to aFraction, and the result is assigned to sum2, then sum is released. So how is it in the next line (sum = sum2), sum holds that value still? Cause doesn't sum now have a reference count of 0 after being released since it was only initialized once. I thought sum2 would have the increased reference count and that would need to be relased after it gets assigned to sum.
Sorry for the noob questions.